【Winform】学习笔记(七)——Checkbox的使用(单选,全选,反选,获取值)

不羁的心 提交于 2020-02-07 00:49:20

多个CheckBox同时使用时,建议将CheckBox放在groupbox中,便于进行全选/非全选、获取选中的CheckBox的值

一、在groupbox中使用

  1. 全选/全不选
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;
        }
    }
}
  1. 单选
//勾选框的选中事件
if ((sender as CheckBox).Checked == true)
{
    foreach (CheckBox chk in (sender as CheckBox).Parent.Controls)
    {
        if (chk != sender)
        {
          chk.Checked = false;
        }
    }
}
  1. 获取选中值
List<string> list = new List<string>();
foreach (CheckBox ck in groupBox1.Controls)
{
    if (ck.Checked)
    {
        list.Add(ck.Text);
    }
}

二、在datagirdview中使用

  1. 全选
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;
    }
}
  1. 反选
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";
    }
}
  1. 单选
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;
    }
}

  1. 获取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列的值
    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!