如果在C#Desktop Application中取消选中其中一个复选框,则会检查标题中的复选框是否已选中并取消选中

时间:2012-09-27 12:00:39

标签: c# .net

我在C#.net Windows应用程序中有一个datagridview,其中有一个复选框列,我添加了一个标题复选框。

添加标题复选框和复选框列的代码是

DataGridViewCheckBoxColumn c1;
CheckBox ckBox;

private void CheckboxSelect_Load(object sender, EventArgs e)
{
c1 = new DataGridViewCheckBoxColumn();
c1.Name = "selection";
c1.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;

this.dgvSelectAll.Columns.Add(c1);
this.dgvSelectAll.Rows.Add();
this.dgvSelectAll.Rows.Add();
this.dgvSelectAll.Rows.Add();
this.dgvSelectAll.Rows.Add();

ckBox = new CheckBox();
Rectangle rect =this.dgvSelectAll.GetCellDisplayRectangle(0, -1, true);
ckBox.Size = new Size(18, 18);
ckBox.Location = rect.Location;
this.dgvSelectAll.Controls.Add(ckBox);
}

是否可以选中所有复选框,然后选中标题复选框,在选中的复选框中取消选中一个,然后在C#.Net Windows Application中取消选中标题?

1 个答案:

答案 0 :(得分:0)

试试这个,

 void dgvSelectAl_CellValueChanged(object sender, DataGridViewCellEventArgs e)
    {
        if (e.ColumnIndex == 0)
        {
            DataGridViewCheckBoxCell cellCheck = (DataGridViewCheckBoxCell)dgvSelectAl[e.ColumnIndex, e.RowIndex];
            if (cellCheck != null)
            {
                if ((bool)cellCheck.Value == true)
                {
                    checkBoxCounter++;
                }
                else
                {
                    checkBoxCounter--;
                }
            }
            if (checkBoxCounter == dgvSelectAl.Rows.Count-1)
            {
                ckBox.Checked = true;
            }
            else if (checkBoxCounter != dgvSelectAl.Rows.Count-1)
            {
                ckBox.Checked = false;
            }
        }
    }