如何获取DataGridView中变更复选框的行号以避免遍历所有行?
优化DataGridView复选框与List的同步逻辑(无需遍历所有行)
直接利用事件参数定位变更行,避免全量遍历
你当前的代码每次点击复选框都遍历所有行完全没必要——CellContentClick事件的DataGridViewCellEventArgs e参数已经包含了点击的行号(e.RowIndex)和列号(e.ColumnIndex),可以直接定位到变更行,只更新对应List元素:
private void dgvObjecten_CellContentClick(object sender, DataGridViewCellEventArgs e) { // 校验:确保点击的是"Import"列,且行号有效(排除表头行) var importColumn = dgvObjecten.Columns["Import"]; if (e.ColumnIndex == importColumn.Index && e.RowIndex >= 0) { // 获取当前复选框的最新状态 bool newImportState = (bool)dgvObjecten.Rows[e.RowIndex].Cells["Import"].Value; // 直接更新List中对应索引的对象属性 Dig1Objecten[e.RowIndex].Import = newImportState; // 仅刷新当前行即可,无需重新绑定整个数据源 dgvObjecten.RefreshRow(e.RowIndex); } }
进阶:实现双向数据绑定,彻底省去手动同步
如果你的自定义数据类型(UDT)实现了INotifyPropertyChanged接口,DataGridView会自动和List中的对象做双向同步——修改复选框时,UDT对象的Import属性会自动更新,List中的数据自然同步,连事件里的手动更新都可以省掉:
第一步:给UDT添加INotifyPropertyChanged实现
public class Dig1Object : INotifyPropertyChanged { private bool _import; public bool Import { get => _import; set { if (_import != value) { _import = value; OnPropertyChanged(nameof(Import)); } } } // 你的其他属性... public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } }
第二步:处理复选框的提交逻辑(可选)
有时候点击复选框边缘可能不会立即触发值变更,添加下面的事件处理确保修改被提交:
private void dgvObjecten_CurrentCellDirtyStateChanged(object sender, EventArgs e) { if (dgvObjecten.IsCurrentCellDirty && dgvObjecten.CurrentCell is DataGridViewCheckBoxCell) { dgvObjecten.CommitEdit(DataGridViewDataErrorContexts.Commit); } }
设置完成后,你甚至可以删掉原来的CellContentClick事件处理——DataGridView会自动把复选框状态同步到List对应的UDT对象中,完全不需要手动遍历或更新。
内容的提问来源于stack exchange,提问作者KevinM
相关产品推荐
相关产品推荐

