gpt4 book ai didi

c# - WinForm 控件绑定(bind)到 List 问题

转载 作者:太空宇宙 更新时间:2023-11-03 11:52:14 24 4
gpt4 key购买 nike

我有一个用于存储数据的列表,我尝试将其项目绑定(bind)到网格、列表框、文本框等,但无法使其正常工作。这是我的代码

class Survey
{
public int Id { get; set; }
public string Desc{ get; set; }
public List<string> Choices { get; set; }
}

.

List<Survey> _surveyList = GetList();
BindingSource _bindingSourceSurveys = new BindingSource { DataSource=_surveyList};
dataGridView1.DataSource = _bindingSourceSurveys;
txtDesc.DataBindings.Add("Text", _bindingSourceSurveys, "Desc",false,DataSourceUpdateMode.OnPropertyChanged,string.Empty);
lstChoices.DataBindings.Add("DataSource" , _bindingSourceSurveys,"Choices" ,false,DataSourceUpdateMode.OnPropertyChanged, string.Empty);

现在我可以在 dataGrid 上看到项目,selectedItem(在 dataGrid 上)在 textBox 上的 Desc 属性值,也可以从 textBox 更改 Desc 属性值。

如果我像那样向我的 selectedItem 列表选项添加一个新选项

(_bindingSourceSurveys.Current as Survey).Choices.Add("NewChoice");

注意:我无法添加到 ListBox.Items,因为它给出了异常,因为我绑定(bind)到此控件的数据源。

ListBox 不显示新项目,如果我从 dataGrid 选择不同的项目并返回我可以看到新添加的选择。

这里有什么问题?还有就是代码没问题,第一次用这个绑定(bind)工具。

最佳答案

当元素发生变化时,您的数据源不会引发事件。一个简单的解决方法是将数据源从 List 更改为 BindingList。

关于c# - WinForm 控件绑定(bind)到 List<T> 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1793997/

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