32

How can I setup custom column names for DataGridView with associated DataSource?

Here is some code:

class Key
{
    public string Value { get; }
    public DateTime ExpirationDate { get; }
}

List<Key> keys = new List<Key>();
...// fill keys collection

DataGridView dataGridView = createAndInitializeDataGridView();
dataGridView.DataSource = keys;

This gives me dataGridView with column names "Value" and "ExpirationDate". How should I proceed to change names to "Key" and "Expire" for example?

1
  • If your data is coming from a database, you can change the column names in your SQL by aliasing them.
    – DOK
    Commented Jun 3, 2011 at 14:23

3 Answers 3

67

Use the DisplayName attribute on your properties to specify column names in your DataGridView:

class Key
{
    [System.ComponentModel.DisplayName("Key")]
    public string Value { get; }
    [System.ComponentModel.DisplayName("Expire")]
    public DateTime ExpirationDate { get; }
} 
1
  • This doesn't work if I am creating new objects based on this object, for example via Inner Joins.
    – TK-421
    Commented Jan 20, 2022 at 13:39
11

You should be able to change the header cells after you've set the datasource:

    if (dataGridView1.Columns["Value"] != null)
        dataGridView1.Columns["Value"].HeaderText = "Key";
    if (dataGridView1.Columns["Expiration"] != null)
        dataGridView1.Columns["Expiration"].HeaderText = "Expire";
2
  • 1
    thanks for the answer. it worked, but Jay Riggs gave another answer that I like more.
    – Bobrovsky
    Commented Jun 3, 2011 at 15:02
  • 1
    Cool, yeh, I like his more as well, that goes in the memory bank :-) Commented Jun 3, 2011 at 18:20
0
public DataTable SetColumnsHeaderName(string[] TagName)
{
    DataTable dt = new DataTable();
    foreach (var item in TagName)
    {
        dt.Columns.Add(item);
    }
    return dt;
}

public void ShowDataGridView()
{
    string[] tag = new string[] { "First Name", "Last Name", "Phone Number", };
    //fill datatable columns Name
    var dt = SetColumnsHeaderName(tag);
    //connect db and fetch table name
    var listx = db.tablename.ToList();
    foreach (var item in listx)
    {
        dt.Rows.Add(new object[] { item.Name, item.Family, item.Phone });
    }
    datagridView.DataSource = dt;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.