C# winfrom 中datagridview中checkbox的使用方法

來源:互聯網
上載者:User

方法一:
private void dgv_zy_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
            int count = Convert.ToInt16(dgv_zy.Rows.Count.ToString());
            for (int i = 0; i < count; i++)
            {
                DataGridViewCheckBoxCell checkCell = (DataGridViewCheckBoxCell)dgv_zy.Rows[i].Cells["cb_check"];
                Boolean flag = Convert.ToBoolean(checkCell.Value);
               if (flag == true)     //尋找被選擇的資料行
                {            
                    checkCell.Value = false;
                }
                else
                   continue;
            }
      }

 

}

擷取選擇的資料

          int count = Convert.ToInt32(dgv_zy.Rows.Count.ToString());
          for (int i = 0; i < count; i++)
            {
                //如果DataGridView是可編輯的,將資料提交,否則處於編輯狀態的行無法取到
             dgv_zy.EndEdit();
                DataGridViewCheckBoxCell checkCell = (DataGridViewCheckBoxCell)dgv_zy.Rows[i].Cells["cb_check"];
               Boolean flag = Convert.ToBoolean(checkCell.Value);
                if (flag == true)     //尋找被選擇的資料行
               {
                   //從 DATAGRIDVIEW 中擷取資料項目
                string z_zcode = dgv_zy.Rows[i].Cells[0].Value.ToString().Trim();

                }
            }

方法二:

如果需要在winform 的資料控制項datagridview 中嵌入checkbox列 (  DataGridViewCheckBoxCell ),
在程式的執行中有可能需要像純粹的checkbox控制項的selectedindexchanged事件一樣的事件來捕捉其狀態的改變

我覺得比較好的方式是用datagridview 控制項的cellcontentclick事件   例如:

如果嵌入的 DataGridViewCheckBoxCell 列在第一列,判斷狀態並添加處理事件可以為:

  private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

            if (e.ColumnIndex == 0 && e .RowIndex != -1)
            {

                     //擷取控制項的值

                    MessageBox.Show(this.dataGridView1.Rows[e.RowIndex].Cells[0].EditedFormattedValue.ToString());

                //或者可以做其他事件處理常式

            }

}

需要注意的是執行此事件是需要屏蔽其他datagridview儲存格的cellcontentclick事件 ,即讓除了 DataGridViewCheckBoxCell 列

之外的所有列的ReadOnly=True;

 

 

  在擷取datagridview中checkbox列的值得時候 一定要用 EditedFormattedValue屬性,此屬性擷取的是編輯以後數值 而value 和

FormattedValue返回的往往是編輯以前的數值,而其重複單擊的時候往往會出現錯誤(無法確定是編輯前還是編輯後的數值: 主要

原因是焦點問題,需要先移動焦點使datagridview擷取更改後的資料在區擷取他 就沒有問題了,所以以後用去擷取資料前先要移出

datagridview中的焦點!!!),所以一定要用EditedFormattedValue來擷取屬性值

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.