【问题标题】:Datagridview not updating correctlyDatagridview 没有正确更新
【发布时间】:2018-01-30 10:41:53
【问题描述】:

我是 C# 的新手,我正在尝试将对象列表输入到 datagridview 中。每次单击按钮时,我都会不断将项目添加到此列表中,并且 datagridview 应该通过将其数据源设置回列表来刷新。

这里是列表:

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

这是添加到列表并刷新列表的代码:

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

列表将使用第一项更新,但是当我尝试添加另一个项时,它似乎运行代码块,但实际上并未将其添加到数据网格视图中。有人能帮忙吗?我是否犯了一个我看不到的简单错误?

【问题讨论】:

  • 尝试刷新或使DataGridView无效?另外,为什么要绑定到List&lt;Models.OrderItem&gt; 而不是只使用DataTable
  • 我相信您可能必须将 DataSource 设置为 null,然后将其设置为您的列表,然后在网格上调用 ResetBindings。
  • 不幸的是它不起作用:c,Dan 的解决方案
  • 究竟是什么不起作用?重置DataSource ?
  • 感谢 WHEELS73,它成功了。在将数据源重置为列表之前将数据源设置为 null 似乎可以解决问题。

标签: c# datagridview


【解决方案1】:

如前所述,

将源设置为空,重新引用列表,然后重置绑定

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

您可能想尝试省略空值。我不记得如果没有空值,这是否有效。

【讨论】:

    猜你喜欢
    • 2017-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多