views:

33

answers:

4

I have a custom Order class, groups of which are stored in List<Order> and a DataGridView. I think the problem is in my implementation so here's how I'm using it:

In the form enclosing DataGridView (as 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;
    }

Then in another form that adds an Order:

// 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);
}

From what I can tell from the console this is added successfully. I thought the DataGrid would be updated automatically after this since Orders has changed - is there something I'm missing?

The DataGrid accepts the class since it generates columns from the members.

A: 

You need to rebind the data on your DataGrid.

Jamie Chapman
A: 

Shouldn't you rebind the DataGrid after the underlying data source is updated?

Use the code:

OrdersDataGrid.DataSource = Orders;
OrdersDataGrid.DataBind();
bth
I looked up DataBind but it doesn't seem to exist in DataGridView.
Ross
DataBind is ASP.NET specific. The question is about WinForms.
Foole
+1  A: 

Since you can't use DataBind on a DataGridView that's uses an object list as it's DataSource here's the solution I found to this:

  1. First replace your List<T> with BindingList<T> - essentially the same thing, except the BindingList acts like DataBind().

  2. Change your T to implement System.ComponentModel.INotifyPropertyChanged:

This involves adding a property:

public event PropertyChangedEventHandler PropertyChanged;

Adding to each variable's set block:

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

And adding another method:

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

Sources: Binding a DataGridView to a Collection, Info on converting List to BindingList

Ross
A: 

You have to Bind new data to your datagrid using

Gridview1.DataBind();

note that whenever you update some list, which is binded to a gridview or any other presenter list control, it just update the list not gridview.

if you really do not like to rebind your Item use IronPython which provided in .net 3.5

Nasser Hadjloo