How can I setup custom column names for DataGridView with associated DataSource?
Here is some code:
class Key
{
public string Value { get; }
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";
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; }
}
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;
}