0

我添加了动态选项卡,这些选项卡具有具有 DataGridCheckBoxColumn 的动态数据网格以及选项卡上的一个动态复选框,该选项卡触发选择所有数据网格复选框。

我正在尝试按照这些方式实现一些东西。

private void cbSelectAll_CheckedChanged(object sender, EventArgs e)
{

    if (cbSelectAll.Checked)
    {
        foreach (DataGridViewRow row in relatedPatientsDG.Rows)
        {
            row.Cells[0].Value = true;
        }
    }
    else
    {
        foreach (DataGridViewRow row in relatedPatientsDG.Rows)
        {
            row.Cells[0].Value = false;
        }
    }
}

但是这种方法也是动态的,它需要验证选择了哪个选项卡/数据网格 DataGridCheckBoxColumn,因为我正在选项卡上动态创建所有内容。

例如,如果我有一个名为relatedDG 的dataGrid 有DataGridColumnCheckBox,那么触发全选和取消全选的事件方法就像。我需要进行类似的更改,但对于动态 datagridcheckbox,因此没有任何内容是硬编码的。

private void cbSelectAllSameVisits_CheckedChanged(object sender, EventArgs e)
{
    if (cbSelectAllSameVisits.Checked)
    {
        foreach (DataGridViewRow row in relatedDG.Rows)
        {
            row.Cells[0].Value = true;
        }

    }
    else
    {
        foreach (DataGridViewRow row in relatedDG.Rows)
        {
            row.Cells[0].Value = false;
        }
    }
}
4

1 回答 1

0

您可以利用每一对网格和复选框都在同一个标​​签页上的事实——它们都是同一个容器控件的子控件。

这允许您拥有一个附加到CheckedChanged创建时所有复选框的事件的方法:

private void checkBox_CheckedChanged(object sender, EventArgs e)
{
    CheckBox cb = sender as CheckBox;
    DataGridView dg = cb.Parent.Controls.Cast<Control>()
                        .Where(c => c.GetType() == typeof(DataGridView))
                        .FirstOrDefault() as DataGridView;

    if (dg != null)
    {              
        if (cb.Checked)
        {
            foreach (DataGridViewRow row in dg.Rows)
            {
                row.Cells[0].Value = true;
            }
        }
        else
        {
            foreach (DataGridViewRow row in dg.Rows)
            {
                row.Cells[0].Value = false;
            }
        }           
    }            
}  

该代码使用事件处理程序的 sender 参数来识别被单击的复选框,然后搜索属于第一个 DataGridView 的复选框父级的控件。

于 2012-07-23T22:23:30.997 回答