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

如何解决C#中DataGridView.CurrentRow.get返回null的问题?

解决DataGridView自定义方法中CurrentRow为null的问题

问题原因

调用SaveData方法时dataGridView1.CurrentRow返回null,说明此时DataGridView没有选中任何行,也无处于编辑状态的当前行。按钮点击事件中正常运行,是因为用户操作时通常会先选中目标行再触发按钮,此时CurrentRow处于有效状态。另外你的代码存在变量名错误:定义的数组是valuess,但循环中使用values[i],这会导致编译失败,需修正为统一变量名。

解决方案

方案1:调用方法前校验选中状态

在调用SaveData前先判断是否有选中行,避免空引用异常:

// 调用SaveData的代码位置
if (dataGridView1.CurrentRow != null)
{
    SaveData(1, "xxx-guid", "张三", DateTime.Now, "正常");
}
else
{
    MessageBox.Show("请先选中要修改的行");
}

方案2:直接传入目标行(推荐)

不依赖控件的CurrentRow状态,将需要修改的行作为参数传入方法,逻辑更清晰可靠:

// 修改后的SaveData方法
public void SaveData(int ID, string Guid, string Name, DateTime Birth, string status, DataGridViewRow targetRow)
{
    if (targetRow == null)
    {
        MessageBox.Show("目标行无效");
        return;
    }

    string[] values = { Name, Birth.ToString("yyyy/MM/dd"), status };
    for (int i = 0; i < 3; i++)
    {
        targetRow.Cells[i].Value = values[i];
    }
}

// 调用示例
if (dataGridView1.CurrentRow != null)
{
    SaveData(1, "xxx-guid", "张三", DateTime.Now, "正常", dataGridView1.CurrentRow);
}
else
{
    MessageBox.Show("请先选中要修改的行");
}

方案3:如果是新增行场景

若需求是新增一行数据而非修改已有行,需先创建新行再添加到DataGridView:

public void SaveData(int ID, string Guid, string Name, DateTime Birth, string status)
{
    DataGridViewRow newRow = new DataGridViewRow();
    newRow.CreateCells(dataGridView1); // 匹配DataGridView的列结构
    string[] values = { Name, Birth.ToString("yyyy/MM/dd"), status };
    for (int i = 0; i < 3; i++)
    {
        newRow.Cells[i].Value = values[i];
    }
    dataGridView1.Rows.Add(newRow);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 02:33:24