How to set column header text for specific column in Datagridview C#
private void datagrid_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
string test = this.datagrid.Columns[e.ColumnIndex].HeaderText;
}
This code will get the HeaderText
value.
For info, if you are binding to a class, you can do this in your type via DisplayNameAttribute
:
[DisplayName("Access key")]
public string AccessKey { get {...} set {...} }
Now the header-text on auto-generated columns will be "Access key".
If you work with visual studio designer, you will probably have defined fields for each columns in the YourForm.Designer.cs
file e.g.:
private System.Windows.Forms.DataGridViewCheckBoxColumn dataGridViewCheckBoxColumn1;
private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn2;
If you give them useful names, you can set the HeaderText
easily:
usefulNameForDataGridViewTextBoxColumn.HeaderText = "Useful Header Text";
dgv.Columns[0].HeaderText = "Your Header";
Dg_View.Columns.Add("userid","User Id");
Dg_View.Columns[0].Width = 100;
Dg_View.Columns.Add("username", "User name");
Dg_View.Columns[0].Width = 100;
there is HeaderText property in Column object, you can find the column and set its HeaderText after initializing grid or do it in windows form designer via designer for DataGrid.
public Form1()
{
InitializeComponent();
grid.Columns[0].HeaderText = "First Column";
//..............
}
More details are here at MSDN. More details about DataGrid are here.