2014-01-11 150 views
1

我在加载数据的Windows窗体中有一个Datagridview。在运行时,我还在此Datagridview中包含了一个复选框列。我的问题是如何知道复选框列中的任何复选框是否已被选中,并且如果复选框已被选中,请启用按钮。我已经使用CellValueChanged事件来执行上述任务,但无法获得所需的结果。如何检查在datagridview列中是否选中复选框

这是我做了什么

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; 
      } 

     } 

回答

0

试试这个代码

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

+0

上面的代码工作,但是当我取消所有复选框,按钮没有被禁用,甚至在其他部分添加button1.Enabled = false – suds

+1

你应该添加调用这个函数在CellValueChanged datagridview并检查复选框的单元格是否为更改值并执行代码的单元格 – Jade

+0

请参阅我的更新代码 – Jade

1

设置false循环

button1.Enabled = false; 

当你发现检查项目之前,将其设置为启用truebreak循环

button1.Enabled = true; 
break; 

code:

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; 
    } 
} 
+0

请注意,我想检查是否有任何一个复选框已被选中。即用户选中列中的任何复选框,应启用按钮,并且如果未选中复选框,则应禁用按钮。 – suds

+0

@SDKLive检查最终代码 – Damith

+0

它不工作:( – suds

相关问题