日期:2014-05-18 浏览次数:21086 次
private void dataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.RowIndex == -1 && e.ColumnIndex == -1)//单击表头
{
bool checkAll = false;
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
if (dataGridView1.Rows[i].Cells[0].Value == null)//没有给checkBox列激活即选中的情况下,直接获取值.ToString会报错
{
checkAll = false;//checkBox列还未激活,即都还为选中
break;
}
else if (dataGridView1.Rows[i].Cells[0].Value.ToString() == "True")
{
string a = dataGridView1.Rows[i].Cells[0].Value.ToString();
checkAll = true;
}
else if (dataGridView1.Rows[i].Cells[0].Value.ToString() != "True")
{
checkAll = false;//有未被选中的记录,则标记全选为false,跳出循环
break;
}
}
if (checkAll == false) //存在未选的记录,则更新为全选
{
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
dataGridView1.Rows[i].Cells[0].Value = true;
}
}
else //如果原为全选状态,则更新为全不选
{
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
dataGridView1.Rows[i].Cells[0].Value = false;
}
//下面的代码都无法彻底清空行选中状态(不是勾上)
dataGridView1.ClearSelection();
dataGridView1.CurrentCell = null;
// dataGridView1.Rows[0].Selected = false;
}
}
}