簡體   English   中英

DataGridView和List <>的DataBinding與BindingSource

[英]DataBinding of DataGridView and List<> with BindingSource

我試圖弄清楚如何使用BindingSource數據綁定工作我希望在更新列表時使用List<>的內容填充DataGridView

當我檢查調試器時,我可以看到List增長並驗證它是否被填充。 我認為BindingSource會在更改List時觸發事件。 但沒有一個是可用的。 如何更改基礎列表時收到通知?

我按照說明操作,並提供以下測試代碼:

    Data d;
    BindingSource bs;

    public Form1()
    {
        InitializeComponent();
        bs = new BindingSource();
        d = new Data();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        bs.DataSourceChanged += new EventHandler(bs_DataSourceChanged);
        bs.ListChanged += new ListChangedEventHandler(bs_ListChanged);
        bs.DataMemberChanged += new EventHandler(bs_DataMemberChanged);
        bs.CurrentChanged += new EventHandler(bs_CurrentChanged);
        bs.CurrentItemChanged += new EventHandler(bs_CurrentItemChanged);

        bs.DataSource = d.list;
        dataGridView1.DataSource = bs;
    }
    // ... all the handling methods caught with a break point in VS.

    private void button1_Click(object sender, EventArgs e)
    {
        d.addOneItem();
    }

List<T>不支持更改事件; BindingList<T>將是支持此場景的良好替代品,如果您的類型T實現了INotifyPropertyChanged ,它還支持項目級別的更改事件。

在3.0及以上版本中,還有ObservableCollection<T> ,其作用類似於BindingList<T> 這一切都歸結為IBindingListIBindingListView等接口。


來自評論; 添加Find to BindingList<T>的2.0 / 3.0示例:

public class MyBindingList<T> : BindingList<T>
{
    public T Find(Predicate<T> predicate)
    {
        if (predicate == null) throw new ArgumentNullException("predicate");
        foreach (T item in this)
        {
            if (predicate(item)) return item;
        }
        return default(T);
    }
}

請注意,在3.5(或帶有LINQBridge和C#3.0的.NET 2.0 / 3.0)中,您不需要這樣做 - 任何LINQ擴展方法都會做同樣的事情。

如果您希望在更改屬性時收到通知,則需要實現INotifyPropertyChanged

請看這里的例子。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM