2011-02-05 17 views
3

dataGridView1我想連接到我的通用列表。爲此,我使用下面的代碼。dataGridView1連接到我的通用列表?

dataGridView1.DataSource = List;

(列表是靜態的)

但我想更新列表通用dataGridView1也得到更新,每次 我應該怎麼辦?

+1

我想了解你,但你的問題是不是真的在正確的英語。如果您不希望GridView在List中的數據更新時進行更新,請勿將List用於數據綁定GridView和更新(無論發生何處)。 – TheGeekYouNeed 2011-02-05 00:51:50

+0

做對吧? dataGridView1.DataSource = null; dataGridView1.DataSource = _List; – 2011-02-05 01:12:48

回答

2

改爲使用BindingList<T>;這提供了蓋子更改通知(添加,刪除等)。它還提供行級通知(用於屬性更改),但前提是您的類型正確實施了INotifyPropertyChanged;所以實現這一點。

如果您的意思是static字段,請重新列出您的「列表是靜態的」,請注意,如果是的話。使用多線程可能會遇到麻煩;我個人不會這麼做 - 但這與問題無關。

例子:

using System; 
using System.ComponentModel; 
using System.Windows.Forms; 

static class Program 
{ 
    class Foo 
    { 
     public int A { get; set; } 
     public string B { get; set; } 
    } 
    [STAThread] 
    static void Main() 
    { 
     Application.EnableVisualStyles(); 
     Application.SetCompatibleTextRenderingDefault(false); 
     using (var form = new Form()) 
     using (var grid = new DataGridView { Dock = DockStyle.Fill }) 
     using (var add = new Button { Dock = DockStyle.Bottom, Text = "add" }) 
     using (var remove = new Button { Dock = DockStyle.Top, Text = "remove" }) 
     { 
      form.Controls.Add(grid); 
      form.Controls.Add(add); 
      form.Controls.Add(remove); 
      var lst = new BindingList<Foo>(); 
      var rnd = new Random(); 
      add.Click += delegate 
      { 
       lst.Add(new Foo { A = rnd.Next(1, 6), B = "new" }); 
      }; 
      remove.Click += delegate 
      { 
       int index = 0; 
       foreach (var row in lst) 
       { // just to illustrate removing a row by predicate 
        if (row.A == 2) { lst.RemoveAt(index); break; } 
        index++; 
       } 
      }; 
      grid.DataSource = lst; 
      Application.Run(form); 
     } 
    } 
}