DataGridView触发current row returns null错误,求代码问题排查
问题根源
- 报错的核心原因是
dataGridView1.CurrentRow为null时你直接访问了它的Cells属性。触发该场景最直接的原因是你点击button3给textBox1赋值时,会立刻触发textBox1_TextChanged事件,此时CurrentRow还未完成上下文绑定或者因为赋值操作导致DataGridView焦点丢失,CurrentRow就会返回null。 - 其他常见触发场景包括:DataGridView未选中任何行、控件尚未完成数据绑定就执行赋值逻辑、开启
AllowUserToAddRows属性时选中了底部的空白新增行。 - 现有代码没有做任何空值校验,一旦CurrentRow、Cells对应项为null时,就会直接抛出运行时异常。
修复方案
首先你需要避免button3给文本框赋值时触发TextChanged事件,同时加上空值判断逻辑,修复后的参考代码如下:
private void button3_Click(object sender, EventArgs e) { // 先解绑TextChanged事件,避免赋值时触发回写 textBox1.TextChanged -= textBox1_TextChanged; textBox2.TextChanged -= textBox2_TextChanged; textBox3.TextChanged -= textBox3_TextChanged; textBox4.TextChanged -= textBox4_TextChanged; textBox5.TextChanged -= textBox5_TextChanged; textBox6.TextChanged -= textBox6_TextChanged; // 加空值校验和新行判断 if (dataGridView1.CurrentRow != null && !dataGridView1.CurrentRow.IsNewRow) { textBox1.Text = dataGridView1.CurrentRow.Cells[0].Value?.ToString() ?? string.Empty; textBox2.Text = dataGridView1.CurrentRow.Cells[1].Value?.ToString() ?? string.Empty; textBox3.Text = dataGridView1.CurrentRow.Cells[2].Value?.ToString() ?? string.Empty; textBox4.Text = dataGridView1.CurrentRow.Cells[3].Value?.ToString() ?? string.Empty; textBox5.Text = dataGridView1.CurrentRow.Cells[4].Value?.ToString() ?? string.Empty; textBox6.Text = dataGridView1.CurrentRow.Cells[5].Value?.ToString() ?? string.Empty; } // 重新绑定事件 textBox1.TextChanged += textBox1_TextChanged; textBox2.TextChanged += textBox2_TextChanged; textBox3.TextChanged += textBox3_TextChanged; textBox4.TextChanged += textBox4_TextChanged; textBox5.TextChanged += textBox5_TextChanged; textBox6.TextChanged += textBox6_TextChanged; } private void textBox1_TextChanged(object sender, EventArgs e) { if (dataGridView1.CurrentRow != null && !dataGridView1.CurrentRow.IsNewRow) { dataGridView1.CurrentRow.Cells[0].Value = textBox1.Text; } } private void textBox2_TextChanged(object sender, EventArgs e) { if (dataGridView1.CurrentRow != null && !dataGridView1.CurrentRow.IsNewRow) { dataGridView1.CurrentRow.Cells[1].Value = textBox2.Text; } } private void textBox3_TextChanged(object sender, EventArgs e) { if (dataGridView1.CurrentRow != null && !dataGridView1.CurrentRow.IsNewRow) { dataGridView1.CurrentRow.Cells[2].Value = textBox3.Text; } } private void textBox4_TextChanged(object sender, EventArgs e) { if (dataGridView1.CurrentRow != null && !dataGridView1.CurrentRow.IsNewRow) { dataGridView1.CurrentRow.Cells[3].Value = textBox4.Text; } } private void textBox5_TextChanged(object sender, EventArgs e) { if (dataGridView1.CurrentRow != null && !dataGridView1.CurrentRow.IsNewRow) { dataGridView1.CurrentRow.Cells[4].Value = textBox5.Text; } } private void textBox6_TextChanged(object sender, EventArgs e) { if (dataGridView1.CurrentRow != null && !dataGridView1.CurrentRow.IsNewRow) { dataGridView1.CurrentRow.Cells[5].Value = textBox6.Text; } }
内容的提问来源于stack exchange,提问作者Who Knows
相关产品推荐
相关产品推荐

