(Winforms)添加复选框事件处理程序以动态创建并更改检查状态

时间:2019-03-07 09:47:44

标签: c#

基于下面的代码示例,这是为了在Panel动态创建复选框,并且它将根据DataTable中的数据反复增加。

private void PanelContentDropDown_CheckBox()
    {
        int count = 1;
        int j = 30;

        if (dt.Rows.Count > 0)
        {
            MyCheckBox cb1 = new MyCheckBox();
            cb1.Name = "mcbAll";
            cb1.Text = "Select All";
            cb1.TextAlign = ContentAlignment.MiddleLeft;
            cb1.Padding = new Padding(6, 0, 0, 0);
            cb1.Location = new Point(10, 10);
            cb1.CheckedChanged += checkedbox_CheckedChanged;
            Panel_ContentDropDown.Controls.Add(cb1);

            foreach (DataRow row in dt.Rows)
            {
                MyCheckBox cb = new MyCheckBox();
                cb.Name = "mcb" + (count.ToString().Length > 1 ? count.ToString() : "0" + count.ToString());
                cb.Text = row.ItemArray[1].ToString();
                cb.TextAlign = ContentAlignment.MiddleLeft;
                cb.Padding = new Padding(6, 0, 0, 0);
                cb.Location = new Point(10, j + 10);
                cb.AutoSize = true;
                cb.Size = new System.Drawing.Size(380, 25);
                cb.CheckedChanged += checkbox_CheckedChanged;
                Panel_ContentDropDown.Controls.Add(cb);
                j = j + 30;
                count++;
            }
            Panel_ContentDropDown.Visible = true;
        }
        else
            checkbox.DropDownHeight = 10;
    }

,我在下面创建了checkbox_CheckedChanged,事实证明还可以。但是,当我为每个或某些复选框添加更改CheckState时,在CheckBox显示的TextBox的计数器将被重复添加。

示例应为:所有选定(111),将变为所有选定(221)

checkbox_CheckedChanged中,我将代码放在下面。 (此代码用于选中所有复选框)

foreach (Control ctrl in Panel_ContentDropDown.Controls)
{
      MyCheckBox mcb = (MyCheckBox)ctrl;
      mcb.Checked = true;
}
cb.Text = "All Selected (" + listContentCmbBox.Count.ToString() + ")";

0 个答案:

没有答案