Custom column names for DataGridView with associated DataSource

36,205

Solution 1

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

Solution 2

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";
Share:
36,205
Bobrovsky
Author by

Bobrovsky

A smart and busy developer. Usually develop iOS and C#/ASP.NET projects. Here are some projects I'm currently involved in: Docotic.Pdf library An easy to use PDF library that can create PDFs from scratch, edit existing PDFs, extract text or images from PDF files, draw and print PDFs and many other things. Beautiful API, affordable prices, great support. LibTiff.Net library Free, open-source port of libtiff library written using C#. May be used in any application that needs to manipulate TIFF files. Natively supports Silverlight. Released under New BSD License.

Updated on June 28, 2020

Comments

  • Bobrovsky
    Bobrovsky almost 4 years

    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?

  • Bobrovsky
    Bobrovsky almost 13 years
    thanks for the answer. it worked, but Jay Riggs gave another answer that I like more.
  • TBohnen.jnr
    TBohnen.jnr almost 13 years
    Cool, yeh, I like his more as well, that goes in the memory bank :-)
  • TK-421
    TK-421 over 2 years
    This doesn't work if I am creating new objects based on this object, for example via Inner Joins.