標籤:
環境:VS2013
系統:win7 32位
問題:在DataGridView中使用列樣式DataGridViewCheckBoxColumn的問題:
(1)介面上通過滑鼠點擊,使DataGridViewCheckBoxColumn列的多個CheckBox狀態發生改變後,當滑鼠仍選中DataGridViewCheckBoxColumn列的某個儲存格時,擷取其狀態時,發現選中的儲存格值擷取結果錯誤;
擷取方法:dr.Cells["CheckItem"].Value.ToString()
foreach (DataGridViewRow dr in DgvSoftUp.Rows) { if (dr.Cells["CheckItem"].Value != null) { if (Convert.ToBoolean(dr.Cells["CheckItem"].Value.ToString())) { …… } } }
解決方案(來源於http://www.cnblogs.com/gossip/archive/2008/12/02/1346047.html):
在DataGridView的CurrentCellDirtyStateChanged事件中增加:DgvSoftUp.CommitEdit(DataGridViewDataErrorContexts.Commit);
private void DgvSoftUp_CurrentCellDirtyStateChanged(object sender, EventArgs e) { DgvSoftUp.CommitEdit(DataGridViewDataErrorContexts.Commit); }
(2)通過代碼設定CheckBox狀態時,當儲存格選中狀態時,狀態設定無效。
設定代碼如下:
foreach (DataGridViewRow dr in DgvSoftUp.Rows) { dr.Cells["CheckItem"].Value = true; }
解決辦法,在設定之後,增加EndEdit():
DgvSoftUp.EndEdit();
DataGridViewCheckBoxColumn的問題