不知道你們有沒有這樣的經驗,當點擊或者取消datagridview的checkbox列時,比較難得到其狀態是選中仍是未選中,進而很差進行其它操做,下面就列出它的解決辦法:html
主要用到了DataGridView的CurrentCellDirtyStateChanged和CellValueChanged兩個事件post
CurrentCellDirtyStateChanged事件是提交對checkbox狀態的修改this
CellValueChanged事件是當狀態提交後,也就是單元格值改變後作一些其它的操做spa
(1). CurrentCellDirtyStateChanged事件代碼:code
void PositionListDataView_CurrentCellDirtyStateChanged( object sender, EventArgs e) { DataGridView grid = sender as DataGridView; if (grid != null ) { grid.CommitEdit(DataGridViewDataErrorContexts.Commit); } }
(2). CellValueChanged事件代碼: orm
void PositionListDataView_CellValueChanged( object sender, DataGridViewCellEventArgs e) { DataGridView grid = sender as DataGridView; if (grid != null && e.RowIndex >= 0 ) { if (grid.Columns[e.ColumnIndex].Name == " Check " ) { DataTable dt = grid.DataSource as DataTable; int pstnID = Convert.ToInt32(dt.Rows[e.RowIndex][ 1 ]); DataGridViewCheckBoxCell checkbox = grid.Rows[e.RowIndex].Cells[e.ColumnIndex] as DataGridViewCheckBoxCell; // 得到checkbox列單元格 int result = 0 ; if (checkbox != null && checkbox.Value.ToString() == " 1 " ) { result = cuttingReport.UpdateR_RptRstnStandardAndBlendByCheck( this .reportID,pstnID, 1 , 0 ); } else { result = cuttingReport.UpdateR_RptRstnStandardAndBlendByCheck( this .reportID, pstnID, 0 , 0 ); } if (result < 1 ) { MessageBox.Show( " 修改失敗" , " 提示" , MessageBoxButtons.OK, MessageBoxIcon.Error); } } } }
另外:grid.Columns[e.ColumnIndex].Name == "Check" 中Name的值,是在生成DataGridView的Columns時添加的:htm
new DataGridViewCheckBoxColumn() { HeaderText = "Check", DataPropertyName = "Checked", Visible = true, Width = 45, Frozen = true, Name = "Check", TrueValue = 1, FalseValue = 0, IndeterminateValue = 0 }blog
原文參考:http://www.cnblogs.com/gossip/archive/2008/12/02/1346047.html事件