Datagridview无法正确更新 [英] Datagridview not updating correctly
问题描述
我是C#的新手,正在尝试将一个对象列表输入到datagridview中。每次单击按钮时,我都会不断向该列表中添加项目,并且datagridview应该通过将其数据源设置回列表来刷新。
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.
这是列表:
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;
}
该列表将与第一个项目一起更新,但是当我尝试添加另一个项目时它似乎在运行代码块,但是实际上并没有将其添加到datagrid视图中。有人能帮忙吗?我犯了一个我看不到的简单错误吗?
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?
推荐答案
如上所述,
将源设置为null,重新引用列表,然后重置绑定
Set the source to null, re-ref the list, then reset bindings
ItemOnOrderDataGrid.DataSource = null;
ItemOnOrderDataGrid.DataSource = orderitemlist;
ItemOnOrderDataGrid.ResetBindings();
您可能想尝试省略null。我不记得这是否可以不使用null。
You may want to try omitting the null. I can't recall if this works without the null.
这篇关于Datagridview无法正确更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!