DataGridView RowEnter事件触发NullReferenceException异常求助
排查DataGridView RowEnter事件中的NullReferenceException异常
嘿,我来帮你分析这个问题哈——你遇到的NullReferenceException是因为在RowEnter事件触发时,dataGridView1.CurrentRow可能为null,哪怕你已经判断了Rows.Count > 0。
异常原因分析
RowEnter事件的触发时机不止是用户主动点击行:比如DataGridView初始化过程中、行被删除后焦点转移时,都可能触发这个事件。这时候虽然总行数大于0,但系统还没给CurrentRow正确赋值,就会导致它为null。- 另外,就算
CurrentRow存在,直接调用Value.ToString()也有风险——如果单元格本身的值是null,同样会抛出NullReferenceException。
解决办法
我们需要在代码里增加两层安全判断:先确认当前行有效,再检查单元格值是否为null,再进行赋值。这里给你两种可行的修改方案:
方案一:直接检查CurrentRow是否有效
private void dataGridView1_RowEnter(object sender, DataGridViewCellEventArgs e) { // 先判断当前行是否存在,这比判断总行数更准确 if (dataGridView1.CurrentRow != null) { // 用空传播+空合并运算符,避免Value为null时ToString()报错 txtMaNCC.Text = dataGridView1.CurrentRow.Cells["MaNCC"].Value?.ToString() ?? string.Empty; txtTenNCC.Text = dataGridView1.CurrentRow.Cells["TenNCC"].Value?.ToString() ?? string.Empty; txtDiaChi.Text = dataGridView1.CurrentRow.Cells["DiaChi"].Value?.ToString() ?? string.Empty; txtDienThoai.Text = dataGridView1.CurrentRow.Cells["DienThoai"].Value?.ToString() ?? string.Empty; txtNguoiDaiDien.Text = dataGridView1.CurrentRow.Cells["NguoiDaiDien"].Value?.ToString() ?? string.Empty; } }
方案二:利用事件参数的RowIndex获取行(更可靠)
private void dataGridView1_RowEnter(object sender, DataGridViewCellEventArgs e) { // 检查行索引是否在有效范围内 if (e.RowIndex >= 0 && e.RowIndex < dataGridView1.Rows.Count) { DataGridViewRow currentRow = dataGridView1.Rows[e.RowIndex]; txtMaNCC.Text = currentRow.Cells["MaNCC"].Value?.ToString() ?? string.Empty; txtTenNCC.Text = currentRow.Cells["TenNCC"].Value?.ToString() ?? string.Empty; txtDiaChi.Text = currentRow.Cells["DiaChi"].Value?.ToString() ?? string.Empty; txtDienThoai.Text = currentRow.Cells["DienThoai"].Value?.ToString() ?? string.Empty; txtNguoiDaiDien.Text = currentRow.Cells["NguoiDaiDien"].Value?.ToString() ?? string.Empty; } }
关键说明
- 方案二用
e.RowIndex获取触发事件的行,比依赖CurrentRow更可靠,因为RowEnter事件的e.RowIndex就是当前进入的行的索引,只要索引有效,就能安全拿到行对象。 ?.是C#的空传播运算符:如果前面的对象为null,就不会执行后面的方法,直接返回null;?? string.Empty是把null转换成空字符串,避免文本框显示"null"或者报错。
内容的提问来源于stack exchange,提问作者Higanbana
相关产品推荐
相关产品推荐

