2010-03-12 86 views
0

我有一個自定義Order類,其中的組存儲在List<Order>和DataGridView中。我認爲這個問題是在我的實現,因此這裏是我如何使用它:添加到DataGridView的新記錄未顯示

在封閉的形式DataGridView(如OrdersDataGrid):

public partial class MainForm : Form 
{ 

    public static List<Order> Orders; 

    public MainForm() 
    { 
     // code to populate Orders with values, otherwise sets Orders to new List<Order>(); 
     OrdersDataGrid.DataSource = Orders; 
    } 

然後以另一種形式,增加了一項命令:

// Save event 
public void Save(object sender, EventArgs e) { 
    Order order = BuildOrder(); // method that constructs an order object from form data 
    MainForm.Orders.Add(order); 
} 

從控制檯中我可以看出這已成功添加。我認爲DataGrid會在這之後自動更新,因爲Orders已更改 - 是否有某些我錯過?

DataGrid接受該類,因爲它從成員生成列。

回答

1

因爲你不能在一個DataGridView這是使用的DataBind使用對象名單,因爲它的DataSource這裏,我發現這個問題的解決:

  1. 首先更換你的List<T>BindingList<T> - 基本上是一樣的,除了BindingList就像DataBind()一樣。

  2. 更改T實施System.ComponentModel.INotifyPropertyChanged

這包括添加一個屬性:

public event PropertyChangedEventHandler PropertyChanged; 

添加到每個變量的set塊:

public string Name 
{ 
    get { return this.CustomerName; } 
    set { 
     this.CustomerName = value; 
     this.NotifyPropertyChanged("Name"); 
    } 
} 

並添加另一種方法:

private void NotifyPropertyChanged(string name) 
{ 
    if (PropertyChanged != null) 
    { 
     PropertyChanged(this, new PropertyChangedEventArgs(name)); 
    } 
} 

來源:Binding a DataGridView to a CollectionInfo on converting List to BindingList

0

您需要重新綁定DataGrid上的數據。

0

不應該在基礎數據源更新後重新綁定DataGrid嗎?

使用代碼:

OrdersDataGrid.DataSource = Orders; 
OrdersDataGrid.DataBind(); 
+0

提供我擡起頭來的DataBind,但它似乎並沒有在DataGridView的存在。 – Ross 2010-03-12 13:48:02

+0

DataBind是ASP.NET特有的。問題是關於WinForms。 – Foole 2010-05-12 04:04:52

-1

你必須使用

Gridview1.DataBind(); 

音符綁定新的數據到你的DataGrid,只要你更新了一些名單,這是綁定到一個GridView或任何其他主持人列表控制,它只是更新列表而不是gridview。

,如果你真的不喜歡你重新綁定項目使用IronPython的它在.NET 3.5