C# winfrom怎么获取DaTaGridview控件里CheckBox值

如题所述

第1个回答  推荐于2016-06-12
1 使用 linq
var queryRows = from DataGridViewRow row in dataGridView.Rows
where (bool)row.Cell["CheckBoxColumnName"].Value
select row;
2 常规方法
CheckBox chk =(CheckBox )GridView1 .Rows [i].Cells [j].FindControl ("CheckBox1");
//i为GridView1 的第i行,j为GridView1的第j列

if (chk.Checked)
{
....//如果模板列上的checkbox1被选中,则...
}追问

常规方法里
CheckBox chk =(CheckBox )GridView1 .Rows [i].Cells [j].FindControl ("CheckBox1");
点不出FindControl 我用的是DataGridViewRow

追答

方法一:
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)
{

//获取控件的值

}

}

追问

我知道为什么会那样了 我把循环去了 谢谢你!

本回答被提问者采纳
第2个回答  2012-05-23
DataGridViewCheckBoxCell cbx = (DataGridViewCheckBoxCell)dr.Cells["ckSelected"];
string value = dgvEmpInfo.Rows[i].Cells["ckSelected"].FormattedValue.ToString();
只需判断value值是“true” 还是“false”
相似回答