You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:修复C#中DataGridView添加行时的对象引用未实例化错误

解决“object reference not set to an instance of an object”错误

错误出在table.Rows.Add(num, product, qty, price, totprice);这行,核心原因是OrdersGV.DataSource as DataTable返回了null——订单DataGridView的数据源要么未初始化,要么不是DataTable类型。以下是具体修复方案:

1. 初始化订单DataGridView的数据源

在窗体加载事件中创建并绑定DataTable,确保OrdersGV有合法的数据源:

private void Form_Load(object sender, EventArgs e)
{
    // 创建订单数据表并定义列结构
    DataTable orderTable = new DataTable();
    orderTable.Columns.Add("序号", typeof(int));
    orderTable.Columns.Add("商品", typeof(string));
    orderTable.Columns.Add("数量", typeof(int));
    orderTable.Columns.Add("单价", typeof(int));
    orderTable.Columns.Add("总价", typeof(int));
    // 将数据表绑定到DataGridView
    OrdersGV.DataSource = orderTable;
}

2. 修复商品选择事件中的潜在空引用问题

点击商品表格单元格时,先判断选中行和单元格值是否为空,避免空引用:

private void ProductsGV_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
    // 检查是否有选中行
    if (ProductsGV.SelectedRows.Count == 0) return;
    var selectedRow = ProductsGV.SelectedRows[0];
    
    // 检查单元格值是否为空
    if (selectedRow.Cells[1].Value == null || selectedRow.Cells[3].Value == null) return;
    
    product = selectedRow.Cells[1].Value.ToString();
    price = Convert.ToInt32(selectedRow.Cells[3].Value.ToString());
    flag = 1;
}

3. 优化确认按钮逻辑,增加安全校验

添加数量输入的合法性校验,同时确保table不为空再执行添加操作:

private void button4_Click(object sender, EventArgs e)
{
    if (string.IsNullOrWhiteSpace(OrderQtyTb.Text))
    {
        MessageBox.Show("请输入数量");
        return;
    }
    
    // 安全转换数量为整数
    if (!int.TryParse(OrderQtyTb.Text, out qty))
    {
        MessageBox.Show("请输入有效的数字数量");
        return;
    }
    
    if (flag == 0)
    {
        MessageBox.Show("请选择商品");
        return;
    }
    
    num += 1;
    totprice = qty * price;
    DataTable table = OrdersGV.DataSource as DataTable;
    
    if (table != null)
    {
        table.Rows.Add(num, product, qty, price, totprice);
        flag = 0;
    }
    else
    {
        MessageBox.Show("订单表格未正确初始化");
    }
}

内容的提问来源于stack exchange,提问作者John

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 02:05:44