C# Winforms DataGridView 数据绑定到复杂类型/嵌套属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/683796/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Winforms DataGridView databind to complex type / nested property
提问by B Z
I am trying to databind a DataGridView
to a list that contains a class with the following structure:
我正在尝试将 a 数据绑定DataGridView
到包含具有以下结构的类的列表:
MyClass.SubClass.Property
When I step through the code, the SubClass
is never requested.
当我逐步执行代码时,SubClass
从未请求过。
I don't get any errors, just don't see any data.
我没有收到任何错误,只是没有看到任何数据。
Note that I can databind in an edit form with the same hierarchy.
请注意,我可以在具有相同层次结构的编辑表单中进行数据绑定。
采纳答案by Chris Holmes
Create a property on MyClass that exposes the SubClass.Property. Like so:
在 MyClass 上创建一个公开 SubClass.Property 的属性。像这样:
public class MyClass
{
private SubClass _mySubClass;
public MyClass(SubClass subClass)
{
_mySubClass = subClass;
}
public PropertyType Property
{
get { return _subClass.Property;}
}
}
回答by gcores
You can't bind a DataGridView to nested properties. It's not allowed.
您不能将 DataGridView 绑定到嵌套属性。这不被允许。
One solution is to use this ObjectBindingSourceas a Datasource.
一种解决方案是将此ObjectBindingSource用作数据源。
回答by vizmi
You can add a handler to DataBindingComplete event and fill the nested types there. Something like this:
您可以向 DataBindingComplete 事件添加处理程序并在那里填充嵌套类型。像这样的东西:
in form_load:
在 form_load 中:
dataGridView.DataBindingComplete += new DataGridViewBindingCompleteEventHandler(dataGridView_DataBindingComplete);
later in the code:
稍后在代码中:
void dataGridView_DataBindingComplete(object sender,
DataGridViewBindingCompleteEventArgs e)
{
foreach (DataGridViewRow row in dataGridView.Rows)
{
string consumerName = null;
consumerName = ((Operations.Anomaly)row.DataBoundItem).Consumer.Name;
row.Cells["Name"].Value = consumerName;
}
}
It isn't nice but works.
这不是很好,但有效。
回答by Ricardo Pratti
You can use Linq too!
您也可以使用 Linq!
Get your generic list and use .select for choose the fields like the exemple below:
获取您的通用列表并使用 .select 选择如下示例所示的字段:
var list = (your generic list).Select(i => new { i.idnfe, i.ide.cnf }).ToArray();
if (list .Length > 0) {
grid1.AutoGenerateColumns = false;
grid1.ColumnCount = 2;
grid1.Columns[0].Name = "Id";
grid1.Columns[0].DataPropertyName = "idnfe";
grid1.Columns[1].Name = "NumNfe";
grid1.Columns[1].DataPropertyName = "cnf";
grid1.DataSource = lista;
grid1.Refresh();
}