我试图在DataGridView中使用自己的标题文本,该文本将从数据库自动填充。我尝试过dataGridView1.AutoGenerateColumns = false
,然后执行类似创建列的操作:
void createSearchResultHeader()
{
foreach(var prop in typeof(DB.Message).GetProperties())
{
var display =
typeof(DB.Message)
.GetProperty(prop.Name)
.GetCustomAttributes(typeof(System.ComponentModel.DisplayNameAttribute), inherit: false)
.FirstOrDefault() as System.ComponentModel.DisplayNameAttribute;
DataGridViewColumn col = new DataGridViewTextBoxColumn();
col.HeaderText = display.DisplayName;
dataGridView1.Columns.Add(col);
}
}
然后将结果加载:
using (var conn = createConnection())
using (var da = new SQLiteDataAdapter(createCommand(conn)))
using (var dt = new DataSet())
{
dt.Locale = System.Globalization.CultureInfo.InvariantCulture;
da.Fill(dt);
dg.DataSource = dt.Tables[0].DefaultView;
}
问题是,使用dataGridView1.AutoGenerateColumns = false
创建了列(我在Form的加载中调用createSearchResultHeader()
),但是数据库的结果为空,但是如果我更改dataGridView1.AutoGenerateColumns = true
,则数据库的结果为已成功加载,但它添加了自己的列,而不是使用createSearchResultHeader()
创建的列。我该如何解决?
答案 0 :(得分:1)
您必须设置DataGridViewColumn.DataPropertyName:
void createSearchResultHeader()
{
foreach(var prop in typeof(DB.Message).GetProperties())
{
var display =
typeof(DB.Message)
.GetProperty(prop.Name)
.GetCustomAttributes(typeof(System.ComponentModel.DisplayNameAttribute), inherit: false)
.FirstOrDefault() as System.ComponentModel.DisplayNameAttribute;
DataGridViewColumn col = new DataGridViewTextBoxColumn();
col.HeaderText = display.DisplayName;
col.DataPropertyName = prop.Name; // Add this
dataGridView1.Columns.Add(col);
}
}