C# 如何将DataGridView选中行值赋值到窗体TextBox文本框
问题原因
- 核心错误为
SelectionChanged事件触发时每次都实例化了全新的DataGridView对象,该对象和窗体上用户实际操作的DataGridView控件无关联,新实例的SelectedCells属性永远为空,因此赋值逻辑始终不会执行。 - 额外注意:该事件需要绑定到窗体上实际存在的DataGridView控件的
SelectionChanged事件,不要绑定到DataTable相关事件上。
修复后代码
private void dgv_SelectionChanged(object sender, EventArgs e) { // 直接获取触发事件的DataGridView对象,不需要手动实例化 DataGridView dgv = sender as DataGridView; // 增加空判断避免运行时报错 if (dgv == null || dgv.CurrentRow == null || dgv.SelectedCells.Count <= 0) { return; } active_Description.Text = Convert.ToString(dgv.CurrentRow.Cells["Description"].Value); active_Cost.Text = Convert.ToString(dgv.CurrentRow.Cells["Cost"].Value); active_Diameter.Text = Convert.ToString(dgv.CurrentRow.Cells["Diameter"].Value); active_Last_Used.Text = Convert.ToString(dgv.CurrentRow.Cells["CareTaker"].Value); active_Location.Text = Convert.ToString(dgv.CurrentRow.Cells["Location"].Value); active_OAL.Text = Convert.ToString(dgv.CurrentRow.Cells["OAL"].Value); active_Vendor.Text = Convert.ToString(dgv.CurrentRow.Cells["Vendor"].Value); }
可选优化方案
如果不需要依赖DataGridView的交互状态,也可以直接从绑定的DataTable中取值:通过dgv.CurrentRow.DataBoundItem即可拿到当前选中行对应的DataRow对象,跳过控件层直接操作数据源性能更高。
内容的提问来源于stack exchange,提问作者Joe Fisher
相关产品推荐
相关产品推荐

