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

问题描述 投票:0回答:1

我创建了一个小的厨房展示程序来显示食物订单。因此,我动态创建了一个包含表布局面板的面板,该面板包含一个选中的列表框和一个“全部选中”按钮。我的问题是...我在动态创建的每个表格布局面板中都有一个全选按钮,每次单击它时,它都会检查最后创建的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);
}
c# panel tablelayoutpanel checkedlistbox
1个回答
1
投票

首先,我将描述该结构订单= TableLayoutPanelTableLayoutPanel具有1个CheckAll ButtonCheckListBox并且,当您单击到[[CheckAll Button时,您将希望准确检查当前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); } } }
并且在删除订单时,请勿从地图上将其删除。希望对您有所帮助
© www.soinside.com 2019 - 2024. All rights reserved.