簡體   English   中英

如何檢查datagridview列中的復選框是否已選中

[英]how to check whether checkbox is checked in datagridview column

我在加載數據的Windows窗體中有一個Datagridview。 我還在運行時將此Datagridview包含了一個復選框列。 我的問題是我如何知道是否已選中復選框列中的任何復選框,以及是否已選中復選框以啟用按鈕。 我已經使用CellValueChanged事件執行上述任務,但是無法獲得所需的結果。

這就是我所做的

 List<int> ChkedRow = new List<int>();

        for (int i = 0; i <= Datagridview1.RowCount - 1; i++)
        {
            if (Convert.ToBoolean(Datagridview1.Rows[i].Cells["chkcol"].Value) == true)
            {
                button1.Enabled = true;
            }
            else
            {
                button1.Enabled = false;
            }

        }

在循環之前設置為false

button1.Enabled = false;

當您找到選中的項目時,將其設置為Enabled truebreak循環

button1.Enabled = true;
break;

碼:

button1.Enabled = false;
for (int i = 0; i <= Datagridview1.RowCount - 1; i++)
{

    if (Convert.ToBoolean(Datagridview1.Rows[i].Cells["chkcol"].Value))
    {
        button1.Enabled = true;
        break;
    }
}

或者你也可以在下面做

button1.Enabled = false;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
   DataGridViewCheckBoxCell cell = row.Cells[colCheckIndex] as DataGridViewCheckBoxCell;
   if (cell.Value == cell.TrueValue){
      button1.Enabled = true;
      break;
    }
}

試試這個代碼

button1.Enabled = false;
foreach (DataGridViewRow row in Datagridview1.Rows)
{
    if (((DataGridViewCheckBoxCell)row.Cells["chkcol"]).Value)
      {
        button1.Enabled = true;
        break;
      }

}

要么

//This will always call the checking of checkbox whenever you ticked the checkbox in the datagrid
private void DataGridView1_CellValueChanged(
    object sender, DataGridViewCellEventArgs e)
{
    if (e.ColumnIndex == [Your column index])
       CheckForCheckedValue();
}

private void CheckForCheckedValue()
{
   button1.Enabled = false;
   foreach (DataGridViewRow row in Datagridview1.Rows)
   {
    if (((DataGridViewCheckBoxCell)row.Cells["chkcol"]).Value)
      {
        button1.Enabled = true;
        break;
      }
   }
}

注意不要忘記檢查Null值,如果它為NULL,請執行一些操作

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM