gpt4 book ai didi

c# - 使用 DataGridView 的 WinForms 数据绑定(bind)

转载 作者:行者123 更新时间:2023-11-30 15:35:55 34 4
gpt4 key购买 nike

虽然我会发布这个,因为在花了几个小时试图解决这个问题之后我一无所获。首先,我完全知道 WinForms 中的数据绑定(bind)并不是最好的。也就是说它在大多数情况下都有效。

在我的场景中,我有一个绑定(bind)源,它是我的表单的主控。用于此绑定(bind)源的对象具有一些简单的属性和两个绑定(bind)列表作为属性。此类和绑定(bind)列表的类类型都实现 INotifyPropertyChanged。在我的表单上,我有两个 DataGridView 用于显示绑定(bind)列表属性的内容。

这也是在设计时通过数据绑定(bind)完成的。我有两个绑定(bind)源,每个绑定(bind)源使用主绑定(bind)源作为数据源,然后使用各自的绑定(bind)列表属性作为数据成员。

到目前为止,我认为这是相当标准的。

为了更新这些列表中的内容,我使用按钮来显示创建新项目的表单,然后我使用 BindingList.Add() 将其添加到列表中。

现在在代码中,如果您进行调试,项目会出现在列表中,但是网格不会更新。但是,如果我向仅使用一个列表绑定(bind)源的表单添加一个列表框,那么两个网格都会按预期开始刷新。

如果有任何不清楚的地方,我深表歉意,我已经尽力解释了一个令人困惑的情况。

任何想法都会有所帮助,因为我真的不想使用隐藏的列表框。

最佳答案

这段代码对我来说很好用

BindingList<Foo> source; // = ...
private void Form1_Load(object sender, EventArgs e)
{
this.dataGridView1.DataSource = new BindingSource { DataSource = source };
this.dataGridView2.DataSource = new BindingSource { DataSource = source, DataMember = "Children" };
}

private void button1_Click(object sender, EventArgs e)
{
source.Add(new Foo { X = Guid.NewGuid().ToString() });
}

private void button2_Click(object sender, EventArgs e)
{
source[0].Children.Add(new FooChild { Y = Guid.NewGuid().ToString() });
}

与模型

public class Foo : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;

private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}

string x;
public string X
{
get { return x; }
set
{
x = value;
this.NotifyPropertyChanged();
}
}

BindingList<FooChild> children;
public BindingList<FooChild> Children
{
get { return children; }
set
{
children = value;
this.NotifyPropertyChanged();
}
}
}

public class FooChild : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;

private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}

string y;
public string Y
{
get { return y; }
set
{
y = value;
this.NotifyPropertyChanged();
}
}
}

两个网格都得到刷新。

希望对你有帮助

编辑

我更改了 Form1_Load 实现

关于c# - 使用 DataGridView 的 WinForms 数据绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14360637/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com