检查指定的已选中列表框中的所有项目c#

时间:2019-09-26 08:19:40

标签: c# panel tablelayoutpanel checkedlistbox

我创建了一个小的厨房展示程序来显示食物订单。因此,我动态创建了一个包含表布局面板的面板,该面板包含一个选中的列表框和一个“全部选中”按钮。我的问题是...我在动态创建的每个表格布局面板中都有一个全选按钮,每次单击它时,它都会检查最后创建的CheckedListBox中的所有项目,而不是单击的所有项目。

这是我的代码:

p = new Panel();
p.Size = new System.Drawing.Size(360, 500);
p.BorderStyle = BorderStyle.FixedSingle;
p.Name = "panel";

tpanel = new TableLayoutPanel();
tpanel.Name = "tablepanel";

clb = new CheckedListBox();

tpanel.Controls.Add(b1 = new Button() { Text = "CheckAll" }, 1, 4);
b1.Name = "b1";
b1.Click += new EventHandler(CheckAll_Click);
b1.AutoSize = true;

private void CheckAll_Click(object sender, EventArgs e)
{

    var buttonClicked = (Button)sender;                        
    var c = GetAll(this, typeof(CheckedListBox));

    for (int i = 0; i < c.Count(); i++)
    {
        \\any help
    }
}

public IEnumerable<Control> GetAll(Control control, Type type)
{
    var controls = control.Controls.Cast<Control>();
    return controls.SelectMany(ctrl => GetAll(ctrl, type)).Concat(controls).Where(c => 
    c.GetType() == type);
}

1 个答案:

答案 0 :(得分:1)

首先,我将描述该结构
Order = TableLayoutPanel
TableLayoutPanel 具有1个 CheckAll 按钮 CheckListBox
而且,当您单击以单击 CheckAll 按钮时,它会准确检查当前 TableLayoutPanel 中的所有项目。
所以尝试这段代码

class XForm : Form {
    // create Dictionary to store Button and CheckListBox
    IDictionary<Button, CheckListBox> map = new Dictionary<Button, CheckListBox> ();

    // when you create new order (new TableLayoutPanel)
    // just add map Button and CheckListBox to map
    private void CreateOrder () {
        var panel = new Panel ();
        panel.Size = new System.Drawing.Size (360, 500);
        panel.BorderStyle = BorderStyle.FixedSingle;
        panel.Name = "panel";

        var table = new TableLayoutPanel ();

        var checklistBox = new CheckedListBox ();
        var button = new Button () { Text = "CheckAll" };

        table.Controls.Add (button, 1, 4);
        button.Name = "b1";
        button.Click += new EventHandler (CheckAll_Click);
        button.AutoSize = true;
        map[button] = checklistBox;
    }

    // and on event handle
    private void CheckAll_Click (object sender, EventArgs e) {
        var buttonClicked = (Button) sender;
        var c = map[buttonClicked];
        if (c == null) return;
        for (int i = 0; i < c.Items.Count; i++)
        {
            c.SetItemChecked(i, true);
        }
    }
}

在删除订单时也不要将其从地图上删除。
希望对您有帮助