如何使用关联的DataSource为DataGridView设置自定义列名?
以下是一些代码:
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;
这为dataGridView提供了列名“Value”和“ExpirationDate”。我应该如何继续将名称更改为“Key”和“Expire”?
答案 0 :(得分:46)
使用属性上的DisplayName属性在DataGridView中指定列名称:
class Key
{
[System.ComponentModel.DisplayName("Key")]
public string Value { get; }
[System.ComponentModel.DisplayName("Expire")]
public DateTime ExpirationDate { get; }
}
答案 1 :(得分:10)
您应该能够在设置数据源后更改标题单元格:
if (dataGridView1.Columns["Value"] != null)
dataGridView1.Columns["Value"].HeaderText = "Key";
if (dataGridView1.Columns["Expiration"] != null)
dataGridView1.Columns["Expiration"].HeaderText = "Expire";
答案 2 :(得分: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;
}