下面介紹Winform中DataGridView的DataGridViewCheckBoxColumn使用方法:
DataGridViewCheckBoxColumn CheckBox是否選中
在判斷DataGridView中CheckBox選中列的時候,用DataGridViewRow.Cells[0].FormattedValue.ToString()=="True"語句時存在問題,當我們直接點擊CheckBox時,結果顯示未選中,但是如果我們在點擊其他單元格時,結果顯示選中。而用DataGridViewRow.Cells[0].EditedFormattedValue.ToString()=="True"語句時不管怎么樣是選中的狀態。
為什么會有這種結果?
原因:就是FormattedValue是操作提交后的結果,而EditedFormattedValue是當前的結果,不管結果是否已經提交。
所以用DataGridViewRow.Cells[0].EditedFormattedValue.ToString()=="True"判斷選中比較合適
if (dgvDownloadList.Rows.Count > 0) { for (int i = 0; i < dgvDownloadList.Rows.Count; i++) { string _selectValue = dgvDownloadList.Rows[i].Cells["Column1"].EditedFormattedValue.ToString(); if (_selectValue == "True") //如果CheckBox已選中,則在此處繼續編寫代碼 } }
DataGridViewCheckBoxColumn 設置CheckBox默認選中
((DataGridViewCheckBoxCell)dgvDownloadList.Rows[i].Cells["Column1"]).Value = true;
DataGridViewCheckBoxColumn 第一時間獲取CheckBox的選中狀態
當點擊或者取消datagridview的checkbox列時,比較難獲得其狀態是選中還是未選中,進而不好進行其它操作,下面就列出它的解決辦法:
CommitEdit :將當前單元格中的更改提交到數據緩存,但不結束編輯模式
dgvDownloadList.CurrentCellDirtyStateChanged += new EventHandler(dgvDownloadList_CurrentCellDirtyStateChanged); dgvDownloadList.CellValueChanged += new DataGridViewCellEventHandler(dgvDownloadList_CellValueChanged); void dgvDownloadList_CurrentCellDirtyStateChanged(object sender, EventArgs e) { if (dgvDownloadList.IsCurrentCellDirty) { dgvDownloadList.CommitEdit(DataGridViewDataErrorContexts.Commit); } } void dgvDownloadList_CellValueChanged(object sender, DataGridViewCellEventArgs e) { if (dgvDownloadList.Rows.Count > 0) { for (int i = 0; i < dgvDownloadList.Rows.Count; i++) { string _selectValue = dgvDownloadList.Rows[i].Cells["Column1"].EditedFormattedValue.ToString(); if (_selectValue == "True") //如果CheckBox已選中,則在此處繼續編寫代碼 } } }
轉載http://www.cnblogs.com/xucan/archive/2010/12/05/1897025.html