Change column Heading names in DatagridView

ankit goel 766 Reputation points
2022-09-10T09:47:45.343+00:00

I am working on a .NET project where I am trying to change the column heading names in datagridview but for unknown reason I am still unable to do so . Can anyone help me out in this matter

Below is the code and markup for the datagridview that I am using :

this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView1.Location = new System.Drawing.Point(539, 36);
this.dataGridView1.Name = "dataGridView1";
this.dataGridView1.RowHeadersWidth = 51;
this.dataGridView1.RowTemplate.Height = 24;
this.dataGridView1.Size = new System.Drawing.Size(936, 353);
this.dataGridView1.TabIndex = 9;

code :

string query = "SELECT $_LastSaleDate AS 'Last_Sale_Date', $_LastSaleParty AS 'last sale to party', $_LastSalePrice AS 'last sold price', $Name AS 'name of party', $_ClosingBalance AS 'closing balance' FROM ItemMovementAnalysis WHERE ($_ClosingBalance = 1511) AND ($_LastSalePrice = 25) AND ($_LastSaleParty = 'Sumandeep Ji ( Punjab )') and ($_LastSaleDate = '09 Aug 2022') ";
using (OdbcDataAdapter dadapter = new OdbcDataAdapter(query, con))
{
DataTable table = new DataTable();
dadapter.Fill(table);
this.dataGridView1.DataSource = table;
}

Developer technologies Windows Forms
Developer technologies C#
{count} votes

Accepted answer
  1. Laxmikant 221 Reputation points
    2022-09-10T16:02:07.193+00:00

    you can use

    foreach (DataGridViewColumn column in dataGridView.Columns)  
        {  
      
            column.HeaderText = "column name " + "string some string"  
        }  
    

    or

    dataGridView.Columns[0].HeaderText = "column1"  
    dataGridView.Columns[1].HeaderText = "column2"  
      
    dataGridView.Columns[2].HeaderText = "column3"   
    
    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Karen Payne MVP 35,586 Reputation points Volunteer Moderator
    2022-09-10T18:40:55.547+00:00

    No matter how the DataGridView is created I recommend using the Description property of columns in tables for SQL-Server. So in the screenshot below, the first image is what we get from reading table data into a DataTable (this will also work with a DataSet) then the lower screenshot is after using descriptions from a table.

    239765-screenshot.png

    How to achieve this is simple but more code than warranted here.

    You can clone the following GitHub repository to try this out. If this works for you, add the class project to your Visual Studio solution and follow what I did in the forms project.

    239655-se.png

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.