C# DataGridView调用getrefresh刷新后CellClick事件无法填充文本框
失效原因
- 每次调用
getrefresh()时都重新创建BindingSource实例并赋值给dataGridView1.DataSource,该操作会重置DataGridView的部分运行时状态,若你的选中模式为默认的CellSelect,点击单个单元格时不会触发整行选中,导致dataGridView1.SelectedRows.Count为0,自然不会进入填充逻辑。 - 重新绑定数据源后,原有的行选中状态会被清空,部分场景下会出现选中逻辑和新绑定的行数据不匹配的问题。
修复方案
- 显式固定DataGridView的选中模式,避免绑定数据源后配置被重置,在
getrefresh()方法末尾添加以下代码:
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect; dataGridView1.MultiSelect = false;
- 优化数据源绑定逻辑,不要每次刷新都新建
BindingSource和重新给DataGridView赋值数据源,将BindingSource改为窗体全局变量,减少对DataGridView状态的影响:
// 窗体全局声明 private BindingSource _donateBindingSource = new BindingSource(); // 窗体加载事件中一次性绑定DataSource private void Form1_Load(object sender, EventArgs e) { dataGridView1.DataSource = _donateBindingSource; getrefresh(); } // 修改后的getrefresh方法 public void getrefresh() { using(SqlConnection conn = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Chaos\OneDrive\Project\c#\Donation\Database.mdf;Integrated Security=True")) { conn.Open(); SqlDataAdapter MyDA = new SqlDataAdapter("SELECT * from DonateTable", conn); DataTable table = new DataTable(); MyDA.Fill(table); // 直接更新全局BindingSource的数据源即可,不需要重新赋值给DataGridView _donateBindingSource.DataSource = table; } }
- 优化点击事件的取值逻辑,直接从CellClick事件参数中获取点击的行,不依赖
SelectedRows集合,兼容性更强:
// DataGridView的CellClick事件绑定该方法即可,不需要额外调用getclicked private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) { // 过滤点击表头的场景 if(e.RowIndex < 0) return; DataGridViewRow currentRow = dataGridView1.Rows[e.RowIndex]; InputID.Text = currentRow.Cells[0].Value?.ToString() ?? string.Empty; InputFN.Text = currentRow.Cells[1].Value?.ToString() ?? string.Empty; InputLastN.Text = currentRow.Cells[2].Value?.ToString() ?? string.Empty; InputDonate.Text = currentRow.Cells[3].Value?.ToString() ?? string.Empty; InputDate.Text = currentRow.Cells[4].Value?.ToString() ?? string.Empty; }
内容的提问来源于stack exchange,提问作者KojTug
相关产品推荐
相关产品推荐

