0
votes

I'm new-ish to C# and I'm trying to input a list of objects into a datagridview. I constantly add items to this list each time I click a button and the datagridview should refresh by setting it's data source back to the list.

Here is the list:

List<Models.OrderItem> orderitemlist = new List<Models.OrderItem>();

And here is the code that adds to the list and refreshes the list:

 private void btnAddToOrder_Click(object sender, EventArgs e)
    {
        int quantity = Convert.ToInt32(tbAddOrderQuantity.Text);
        int stock = Convert.ToInt32(ItemDataGrid.CurrentRow.Cells[6].Value);
        int newstock = stock - quantity;

        if (newstock < 0)
            MessageBox.Show("You do not have enough items in stock for this.");
        else
        {
            ItemDataGrid.CurrentRow.Cells[6].Value = newstock;

            int itemID = Convert.ToInt32(ItemDataGrid.CurrentRow.Cells[0].Value);
            string itemname = Convert.ToString(ItemDataGrid.CurrentRow.Cells[1].Value);
            int sellprice = Convert.ToInt32(ItemDataGrid.CurrentRow.Cells[5].Value);

            Models.OrderItem item = new Models.OrderItem(itemID, itemname, sellprice, quantity);
            orderitemlist.Add(item);
            RefreshItemsOnOrderData();
            RefreshPrice();
        }
    }

    private void RefreshItemsOnOrderData()
    {
        ItemOnOrderDataGrid.DataSource = orderitemlist;
    }

The list will update with the first item however when I try to add another item it seems to run the block of code however doesn't actually add it to the datagrid view. Is anyone able to help? Have I made a simple error I just can't see?

1
Try refreshing or invalidating the DataGridView? Also, why bind to a List<Models.OrderItem> instead of just using a DataTable? - Dan
I believe you may have to set the DataSource to null, then set it to your list, then call ResetBindings on the grid. - Wheels73
Unfortunately it didn't work :c, Dan's Solution - Luke
what exactly did not work? reseting the DataSource ? - Mong Zhu
THANK YOU WHEELS73, IT WORKED. Setting the datasource to null before resetting its datasource to the list seemed to do the trick. - Luke

1 Answers

0
votes

As mentioned,

Set the source to null, re-ref the list, then reset bindings

        ItemOnOrderDataGrid.DataSource = null;
        ItemOnOrderDataGrid.DataSource = orderitemlist;
        ItemOnOrderDataGrid.ResetBindings();

You may want to try omitting the null. I can't recall if this works without the null.