我的datagridview有2列。 第0列包含处于关闭位置的复选框(默认)。用户可以单击该框并更改状态或已选中。
如何循环查找并查找已检查的内容。这是我的代码
try
{
// This line will cause InvalidCastException
// Specified cast is not valid.
if ((bool)(row.Cells[0]).Value || (CheckState)row.Cells[0].Value == CheckState.Checked)
{
// Do something
MessageBox.Show("Checked");
}
}
catch (NullReferenceException nre)
{
MessageBox.Show("No Rows Have Been Checked");
}
答案 0 :(得分:1)
请参阅this answer中的单行:
List<DataGridViewRow> list = DataGridView1.Rows.Cast<DataGridViewRow>().Where(k => Convert.ToBoolean(k.Cells[CheckBoxColumn1.Name].Value) == true).ToList();
这将为您提供已选中复选框的所有行的列表。
答案 1 :(得分:1)
怎么样:
foreach(DataGridViewRow row in dataGridView.Rows){
if (row.Cells[0].Value != null && (bool)row.Cells[0].Value){
//checked, do something
}
}