C# Winform中DataGridView的DataGridViewCheckBoxColumn CheckBox是否選中

轉載至:http://www.cnblogs.com/xucan/archive/2010/12/05/1897025.html

下面介紹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"判斷選中比較合適 

複製代碼
1 if (dgvDownloadList.Rows.Count > 0)
2 {
3    for (int i = 0; i < dgvDownloadList.Rows.Count; i++)
4    {
5        string _selectValue = dgvDownloadList.Rows[i].Cells["Column1"].EditedFormattedValue.ToString();
6        if (_selectValue == "True")
7           //如果CheckBox已選中,則在此處繼續編寫代碼
8     }
9 
複製代碼

 

DataGridViewCheckBoxColumn 設置CheckBox默認選中

   ((DataGridViewCheckBoxCell)dgvDownloadList.Rows[i].Cells["Column1"]).Value = true;

 

DataGridViewCheckBoxColumn 第一時間獲取CheckBox的選中狀態

  當點擊或者取消datagridview的checkbox列時,比較難獲得其狀態是選中還是未選中,進而不好進行其它操作,下面就列出它的解決辦法: 

  CommitEdit :將當前單元格中的更改提交到數據緩存,但不結束編輯模式  

複製代碼
 1 dgvDownloadList.CurrentCellDirtyStateChanged += new EventHandler(dgvDownloadList_CurrentCellDirtyStateChanged);
 2 dgvDownloadList.CellValueChanged += new DataGridViewCellEventHandler(dgvDownloadList_CellValueChanged);
 3  
 4 void dgvDownloadList_CurrentCellDirtyStateChanged(object sender, EventArgs e)
 5 {
 6     if (dgvDownloadList.IsCurrentCellDirty)
 7     {
 8         dgvDownloadList.CommitEdit(DataGridViewDataErrorContexts.Commit);
 9     }            
10 }
11  
12 void dgvDownloadList_CellValueChanged(object sender, DataGridViewCellEventArgs e)
13 {
14     if (dgvDownloadList.Rows.Count > 0)
15     {
16         for (int i = 0; i < dgvDownloadList.Rows.Count; i++)
17         {
18             string _selectValue = dgvDownloadList.Rows[i].Cells["Column1"].EditedFormattedValue.ToString();
19             if (_selectValue == "True")
20                 //如果CheckBox已選中,則在此處繼續編寫代碼
21         }
22      }
23 }
發佈了18 篇原創文章 · 獲贊 29 · 訪問量 11萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章