将对象添加到列表时,绑定到列表的DataGridView不会反映更改 [英] DataGridView bound to List does not reflect changes when adding objects to the List
问题描述
我想知道要使DataGridView像预期的那样需要做什么:
I wonder what I need to do in order to make the DataGridView behave as expected:
我确实有 List< ioChannel>
(命名为 myList )类型的对象:
I do have a List<ioChannel>
(named myList) of objects of this type:
public class ioChannel
{
public string Name { get; set; }
public int Id { get; set; }
}
我试图将DataGridView绑定到此列表:
I tried to bind the DataGridView to this list:
bs = new BindingSource { DataSource = myList };
dgvChannels.DataSource = bs;
现在,我创建了一个向 myList :
Now I created a button that adds elements to myList:
private void btAddChannel_Click(object sender, EventArgs e)
{
myList.Add(new ioChannel() { Id = myList.Count, Name = "My Channel" });
}
当我按下按钮时,列表中会显示新的 ioChannel
,但 dgvChannels
不会添加任何行。
When I press the button, my List gets populated with new ioChannel
's, but the dgvChannels
does not add any rows. What do I need to do in order to make this happen?
BTW:当 myList
填充一些 ioChannel
,然后将BindingSource分配为DataSource,该获取将正确显示在网格中。
BTW: When myList
gets populated with some ioChannel
´s before assigning the BindingSource as DataSource, the get shown properly in the grid.
推荐答案
正如@Loathing评论的那样, BindingList 也为我工作。它将如何工作:
As @Loathing commented BindingList worked for me too. How it will work :
BindingList<ioChannel> myList = new BindingList<ioChannel>();
dgvChannels.DataSource = myList;
BindingList具有通知列表更改的事件。以便datagridview可以通知自己重绘,检查这个。有关更多信息,请访问 msdn 。
BindingList has event that notifies changes in list. So that datagridview can notified to redraw itself, check this. For more information visit msdn.
这篇关于将对象添加到列表时,绑定到列表的DataGridView不会反映更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!