WinForm控件绑定到列表< T>问题 [英] WinForm Controls binding to a List<T> problem

查看:111
本文介绍了WinForm控件绑定到列表< T>问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

i have a List for storing my data, i try to bind its items to grid,listbox,textbox etc. but cant make it work well. Here is my code

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属性值。

Now i can see items on dataGrid, selectedItem(on dataGrid) Desc property value on textBox and also can change Desc propert value from textBox.

如果我为我的selectedItem列表选项添加了一个新选项,那么

If i add a new choice to my selectedItem List Choices like that

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

注意:我不能添加到ListBox.Items,因为它给了异常,因为我绑定到DataSource的这个控件。

Note: I cant add to ListBox.Items because it give Exception because of i make binding to DataSource of this control.

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

ListBox dont show the new item, if i select a different item from dataGrid and turn back i can see the new added choice.

这里有什么问题?也是这个代码是OK的,这是我第一次使用这个绑定工具。

What is the problem here? Also Is that code is OK, its my first time to use this binding facilities.

推荐答案

你的数据源不会引发事件元素更改。一个简单的修复是将数据源从List更改为BindingList。

Your data source does not raise events when elements gets changed. An easy fix is to change the datasource from List to BindingList.

这篇关于WinForm控件绑定到列表&lt; T&gt;问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆