代码之家  ›  专栏  ›  技术社区  ›  ClarkeyBoy

C#-2问题-引用DataGridView中的单元格会导致空引用错误;无法用DataGridView数据更新数据库

  •  0
  • ClarkeyBoy  · 技术社区  · 14 年前

    到目前为止我所拥有的

    • 链接到客户和代理表的数据集;
    • 绑定到数据集的BindingSource;
    • 绑定到BindingSource的Customer表的CustomerBindingSource;
    • 绑定到BindingSource的代理表的AgentBindingSource;
    • 绑定到CustomerBindingSource的DataGridView,其中AgentID列是绑定到AgentBindingSource的组合框。

    到目前为止,这是工作正常。但是我有几个问题,其中之一是在下面的代码。。。

    守则

    void grdCustomers_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
    {
        DataGridViewRow gvr = grdCustomers.Rows[e.RowIndex];
        String currID = gvr.Cells[0].Value.ToString();
        if (currID.Equals(""))
        {
            gvr.Cells[0].Value = "{id}";
        }
    }
    void button1_Click(object sender, EventArgs e) //Save button for when the user has finished editing.
    {
        foreach (DataGridViewRow gvr in grdCustomers.Rows)
        {
            String currID = gvr.Cells[0].Value.ToString();
            if (currID.Equals("{id}"))
            {
                String g = Guid.NewGuid().ToString();
                gvr.Cells[0].Value = g;
            }
        }
        customerTableAdapter.Update(customerAppDS21.Customer);
    }
    

    问题

    1. 第四行在运行程序时引起问题。这意味着对象引用没有设置为对象的实例。我想这是因为 gvr.Cells[0]

    2. 我无法让DataGridView将数据绑定到数据库。我希望用户能够编辑任何值,但是当他们添加一行时,只有单击Save按钮才能计算id( button1 ).

    如果有人能帮我解决这两个问题,我将不胜感激。

    当做,

    3 回复  |  直到 14 年前
        1
  •  1
  •   Mikael    14 年前

    它是一个空值。单元格的默认值始终为空。这意味着您可以在填充之前阅读它,或者该列没有任何值。在尝试访问它之前,请检查它是否为空。如果为空,则该单元格没有值。

        2
  •  0
  •   DevelopingChris    14 年前

    我的经验是,在cellFormatted事件处理程序中修改单元格的内容更容易。

        3
  •  0
  •   wasim    10 年前

    似乎您添加了一个具有空值的新行,然后将数据分配给它。 尝试更改将行添加到网格的方式