多个CheckBox同时使用时,建议将CheckBox放在groupbox中,便于进行全选/非全选、获取选中的CheckBox的值
一、在groupbox中使用
- 全选/全不选
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
bool flag = this.checkBox1.Checked;
if (flag)
{
foreach (CheckBox ck in groupBox1.Controls)
{
ck.Checked = flag;
}
}
else
{
foreach (CheckBox ck in groupBox1.Controls)
{
ck.Checked = flag;
}
}
}
- 单选
//勾选框的选中事件
if ((sender as CheckBox).Checked == true)
{
foreach (CheckBox chk in (sender as CheckBox).Parent.Controls)
{
if (chk != sender)
{
chk.Checked = false;
}
}
}
- 获取选中值
List<string> list = new List<string>();
foreach (CheckBox ck in groupBox1.Controls)
{
if (ck.Checked)
{
list.Add(ck.Text);
}
}
二、在datagirdview中使用
- 全选
bool flag = this.AllCheckBtn.Checked;//AllCheckBtn为全选勾选框
if (flag)
{
//遍历datagridview中的每一行,判断是否选中,若为选中,则选中
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
dataGridView1.Rows[i].Cells[0].Value = flag;
}
}
else
{
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
dataGridView1.Rows[i].Cells[0].Value = flag;
}
}
- 反选
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
if ((Convert.ToBoolean(dataGridView1.Rows[i].Cells[0].Value) == false))//勾选框在第一列
{
dataGridView1.Rows[i].Cells[0].Value = "True";
}
else if ((Convert.ToBoolean(dataGridView1.Rows[i].Cells[0].Value) == true))
{
dataGridView1.Rows[i].Cells[0].Value = "false";
}
}
- 单选
int count = dataGridView1.Rows.Count;
for (int i = 0; i < count; i++)
{
DataGridViewCheckBoxCell checkCell = (DataGridViewCheckBoxCell)dataGridView1.Rows[i].Cells[0];
Boolean flag = Convert.ToBoolean(checkCell.Value);
if (flag == true)
{
checkCell.Value = false;
}
else
{
continue;
}
}
- 获取datagirdview中选中的值
List<int> list = new List<int>();
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
DataGridViewCheckBoxCell checkCell = (DataGridViewCheckBoxCell)dataGridView1.Rows[i].Cells[0];//勾选框在第一列
Boolean flag = Convert.ToBoolean(checkCell.Value);
if (flag == true)
{
list.Add(int.Parse(dt.Rows[i][1].ToString()));//list中加入第1列的值
}
}
来源:CSDN
作者:CK_233
链接:https://blog.csdn.net/weixin_46262993/article/details/104171401