Custom column names for DataGridView with associated DataSource

Bobrovsky picture Bobrovsky · Jun 3, 2011 · Viewed 33.6k times · Source

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?

Answer

Jay Riggs picture Jay Riggs · Jun 3, 2011

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; }
}