如何将类型化 DataTable 绑定到 DataGridView
使用下面的代码,我尝试自定义 DGV,而不依赖于实际数据库列名称的知识。但这不起作用。我可以知道正确的方法是什么吗?谢谢。
public class MyDataTable : DataTable { ... }
public class MyDataRow : DataRow
{
public FirstProperty { get; set; }
public SecondProperty { get; set; }
public ThirdProperty { get; set; }
}
void LoadDataGridView()
{
DataGridViewTextColumn colFirst = new DataGridViewTextColumn();
dgv.AutoGenerateColumns = false;
...
colFirst.HeaderText = "First Property";
colFirst.DataPropertyName = "FirstProperty"; // doesnt work ?
...
...
dgv.Columns.AddRange = { ... };
dgv.DataSource = new BindingSource(mydatatable);
}
With the below code, I am trying to customise the DGV without relying on the knowledge of the actual database column names. But it does not work. Can I know what is the correct way to do it? Thanks.
public class MyDataTable : DataTable { ... }
public class MyDataRow : DataRow
{
public FirstProperty { get; set; }
public SecondProperty { get; set; }
public ThirdProperty { get; set; }
}
void LoadDataGridView()
{
DataGridViewTextColumn colFirst = new DataGridViewTextColumn();
dgv.AutoGenerateColumns = false;
...
colFirst.HeaderText = "First Property";
colFirst.DataPropertyName = "FirstProperty"; // doesnt work ?
...
...
dgv.Columns.AddRange = { ... };
dgv.DataSource = new BindingSource(mydatatable);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
DataTable
实现(间接*)ITypedList
,它始终优先于反射类型模型。因此,您添加的任何属性在很大程度上与数据绑定目的无关,因为属性定义在任何时候都不涉及反射,而是查看DataTable
上定义的列。或者更简单地说:这行不通,也行不通。
*= 通过
IListSource
返回DefaultView
,它是一个实现ITypedList
的DataView
DataTable
implements (indirectly*)ITypedList
, which always takes precedence over the reflection type model. As a consequence, any properties you add are largely irrelevant for data-binding purposes, since the property definitions don't involve reflection at any point, but instead look at the columns defined on theDataTable
.Or less verbose: that won't work, and can't work.
*= via
IListSource
which returns theDefaultView
, which is aDataView
which implementsITypedList