核心提示:在dataGridView表格重新刷新数据后(如dataGridView1.DataSource = tblDatas;),checkbox复选框的选中状态会被清空,下面代码可以在表格刷新后恢复che...
在dataGridView表格重新刷新数据后(如dataGridView1.DataSource = tblDatas;),checkbox复选框的选中状态会被清空,下面代码可以在表格刷新后恢复checkbox的原来状态。
//首先定义集合
public Dictionary<string, bool> dic = new Dictionary<string, bool>();
//比如checkbox复选框在首列,另外列表中有人ID字段的列
dic.Clear(); //清除集合
foreach (DataGridViewRow row in dataGridView1.Rows)
{
//以所在行的ID值和复选框的状态作为一组集合数据,并保存起来
string key = row.Cells["ID"].Value.ToString();
dic.Add(key, (bool)row.Cells[0].Value);
}
//以ID值做为查找关键字,找出对应复选择的状态并赋值,在dataGridView表格刷新后使用
foreach (DataGridViewRow row in dataGridView1.Rows)
{
string key = row.Cells["ID"].Value.ToString();
if (dic.ContainsKey(key))
{
row.Cells[0].Value = dic[key];
}
}