Custom column names for DataGridView with associated DataSource
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";
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, 2020Comments
-
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 almost 13 yearsthanks for the answer. it worked, but Jay Riggs gave another answer that I like more.
-
TBohnen.jnr almost 13 yearsCool, yeh, I like his more as well, that goes in the memory bank :-)
-
TK-421 over 2 yearsThis doesn't work if I am creating new objects based on this object, for example via Inner Joins.