如何使控件跟随其数据源? [英] How to cause a control follow its datasource?

查看:74
本文介绍了如何使控件跟随其数据源?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一开始,当我将我的集合分配给控件的DataSource时,它会跟随集合中的内容。在我的程序执行期间,当集合发生变化时,我看不到控件内容的任何变化。如何让控件跟随收藏品的最新变化?



我尝试过:



我知道的唯一方法是将DataSource设置为null,然后再将其设置为集合!但我认为,这可能不是一个好主意。

At the beginning, when I assign my collection to a control's DataSource, it follows what is in the collection. During the execution of my program, when the collection changes, I don't see any change in the control's content. How can I make the control follow the latest changes of the collection?

What I have tried:

The only way I know is to set DataSource to null and then set it to the collection again! But I think, this may not be a good idea.

推荐答案

尝试使用BindingList:

Try using a BindingList:
class MyClass
    {
    public string Str { get; set; }
    public int I { get; set; }
    }
BindingList<MyClass> myBindingList = new BindingList<MyClass>();
private void button1_Click(object sender, EventArgs e)
    {
    myBindingList.Add(new MyClass() { Str = "s1", I = 100 });
    myBindingList.Add(new MyClass() { Str = "s2", I = 101 });
    myBindingList.Add(new MyClass() { Str = "s3", I = 102 });
    myBindingList.Add(new MyClass() { Str = "s4", I = 103 });
    myBindingList.Add(new MyClass() { Str = "s5", I = 104 });
    MyDataGridView.DataSource = myBindingList;
    }
private void button2_Click(object sender, EventArgs e)
    {
    myBindingList.Add(new MyClass() { Str = "sX", I = 666 });
    }

每次单击Button2时,都会在DataGridView中添加一个字符串。

Every time you click Button2, a string will be added to teh DataGridView.


这篇关于如何使控件跟随其数据源?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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