C # Changing column headers in a DataGridView

I have a datagridview in my project that populates from an SQL database with the following code:

public cToDoList(string paramUser, DateTime paramDueDate) { string sqlStat = "SELECT * FROM tblDiary " + "WHERE DiaryUserFor = @User " + "AND DiaryDueDate <= @DueDate;"; SqlCommand sqlCom = new SqlCommand(sqlStat); sqlCom.Parameters.Add("@User", SqlDbType.VarChar); sqlCom.Parameters.Add("@DueDate", SqlDbType.Date); sqlCom.Parameters["@User"].Value = paramUser; sqlCom.Parameters["@DueDate"].Value = paramDueDate.Date; cSqlQuery sqlQ = new cSqlQuery(sqlCom, "table"); this.cTable = sqlQ.cQueryResults; } 

The above code works fine and the datagridview fills up, however the column headers are field names from the SQL database which are not very user friendly.

I tried a couple of things to try changing the default column names, but nothing works. While I tried -

 dataToDoList.Columns[0].Name = "TEST1"; dataToDoList.Columns["DiaryCompletedDate"].Name = "TEST2"; 

But do nothing.

Can someone tell me how to change column header names in datagridview please?

+4
source share
5 answers

What are the exact columns you need?

Replace the SELECT * with

  SELECT ColumnName AS 'TEST1', ColumnName2 AS 'TEST2' FROM ...etc 
+2
source

Try DataGridViewColumn.HeaderText and AutoGenerateColumns (MSDN)

Hope this works for you.

+3
source

You want Column.HeaderText , not Column.Name .


Alternatively, set the column properties using the visual constructor, and in the set of form designers

 dataToDoList.AutoGenerateColumns = false; 
+2
source

A simple way would be to explicitly specify the columns you want in SQL.

Those. replace select * (which you probably shouldn't use anyway) with select DiaryCompletedDate [TEST1], OtherColumn [TEST2], .. etc.

+1
source

while data binding to the grid you can change the HeaderText as follows

 this.dataGridView1.Columns["ResourceValue"].HeaderText = Helper.getlocalStringResource("Xinga.LocalStrings.ColumnHeader.ResourceValue"); 
+1
source

Source: https://habr.com/ru/post/1391840/


All Articles