不知道大家有没有这样的经验,当点击或者取消datagridview的checkbox列时,比较难获得其状态是选中还是未选中,进而不好进行其它操作,下面就列出它的解决办法:
主要用到了DataGridView的CurrentCellDirtyStateChanged和CellValueChanged两个事件
CurrentCellDirtyStateChanged事件是提交对checkbox状态的修改
CellValueChanged事件是当状态提交后,也就是单元格值改变后做一些其它的操作
(1). CurrentCellDirtyStateChanged事件代码:
private void dgvOutpatientPricing_CurrentCellDirtyStateChanged(object sender, EventArgs e) { DataGridView grid = sender as DataGridView; if (grid != null) { grid.CommitEdit(DataGridViewDataErrorContexts.Commit); } }
(2). CellValueChanged事件代码:
private void dgvOutpatientPricing_CellValueChanged(object sender, DataGridViewCellEventArgs e) { try { DataGridView grid = sender as DataGridView; if (grid != null && e.RowIndex >= 0 ) { if (grid.Columns[e.ColumnIndex].Name == "Col_IsChecked" ) { DataGridViewCheckBoxCell checkbox = grid.Rows[e.RowIndex].Cells[e.ColumnIndex] as DataGridViewCheckBoxCell; // 获得checkbox列单元格 treatmentEntityList[(pageIndex - 1) * pageSize + e.RowIndex].IsChecked = Convert.ToBoolean(dgvOutpatientPricing.Rows[e.RowIndex].Cells["Col_IsChecked"].Value); } } } catch (Exception ex) { MessageBox.Show(ex.Message, "发生错误", MessageBoxButtons.OK, MessageBoxIcon.Error); return; //throw; } }
另外:grid.Columns[e.ColumnIndex].Name == "Check" 中Name的值,是在生成DataGridView的Columns时添加的:
new DataGridViewCheckBoxColumn() { HeaderText = "Check", DataPropertyName = "Checked", Visible = true, Width = 45, Frozen = true, Name = "Check", TrueValue = 1, FalseValue = 0, IndeterminateValue = 0 }