VS2022.NET中如何用键盘箭头切换DataGridView行并显示值到文本框
解决方案
事件选择优化
CellStateChanged事件会在单元格状态(如选中、编辑状态)发生变化时频繁触发,并非监听行切换的最优选择。推荐使用CurrentCellChanged或SelectionChanged事件,这两个事件会在通过键盘箭头键切换选中行时精准触发。
空值安全处理
直接访问CurrentRow和单元格Value容易引发空引用异常(比如DataGridView无数据、行未选中时),需先进行空值判断。
修正后的代码
Private Sub DataGridView1_CurrentCellChanged(sender As Object, e As EventArgs) Handles DataGridView1.CurrentCellChanged ' 先判断当前行是否有效 If DataGridView1.CurrentRow IsNot Nothing Then ' 为文本框赋值,同时处理单元格值为空的情况 TxtBook.Text = DataGridView1.CurrentRow.Cells(1).Value?.ToString() ?? "" TxtAuthor.Text = DataGridView1.CurrentRow.Cells(2).Value?.ToString() ?? "" TxtPublisher.Text = DataGridView1.CurrentRow.Cells(3).Value?.ToString() ?? "" TxtPublish.Text = DataGridView1.CurrentRow.Cells(4).Value?.ToString() ?? "" txtPage.Text = DataGridView1.CurrentRow.Cells(5).Value?.ToString() ?? "" TxtNote.Text = DataGridView1.CurrentRow.Cells(6).Value?.ToString() ?? "" Else ' 无选中行时清空所有文本框 TxtBook.Clear() TxtAuthor.Clear() TxtPublisher.Clear() TxtPublish.Clear() txtPage.Clear() TxtNote.Clear() End If End Sub
额外配置建议
- 确保DataGridView的
SelectionMode属性设置为FullRowSelect,这样箭头键切换时会选中整行,操作体验更符合预期。 - 确认单元格索引(
Cells(1)、Cells(2)等)与DataGridView的列顺序对应,若后续调整列顺序需同步修改索引值。
内容的提问来源于stack exchange,提问作者Khaled Ali
相关产品推荐
相关产品推荐

