[英]how to check whether checkbox is checked in datagridview column
I have a Datagridview within a windows form which loads data. 我在加载数据的Windows窗体中有一个Datagridview。 I have also included a checkbox column to this Datagridview in run time.
我还在运行时将此Datagridview包含了一个复选框列。 My question is how can i know if any of the checkboxs from the checkbox column has been checked, and if a checkbox has been checked enable a button.
我的问题是我如何知道是否已选中复选框列中的任何复选框,以及是否已选中复选框以启用按钮。 I have used CellValueChanged event to perform above task but unable to get the desired result.
我已经使用CellValueChanged事件执行上述任务,但是无法获得所需的结果。
This is what i have done 这就是我所做的
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;
}
}
set false
before the loop 在循环之前设置为
false
button1.Enabled = false;
when you found checked item, set it as Enabled true
and break
the loop 当您找到选中的项目时,将其设置为Enabled
true
并break
循环
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;
}
}
Or you can do below as well 或者你也可以在下面做
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;
}
}
Try this code 试试这个代码
button1.Enabled = false;
foreach (DataGridViewRow row in Datagridview1.Rows)
{
if (((DataGridViewCheckBoxCell)row.Cells["chkcol"]).Value)
{
button1.Enabled = true;
break;
}
}
or 要么
//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;
}
}
}
NOTE Don't forget to check the for Null value and do something if it is NULL 注意不要忘记检查Null值,如果它为NULL,请执行一些操作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.