流布局面板填充 C#

Flow Layout Panel Population C#

我正在尝试使用 ComboBoxes 和 NumbericUpDowns 填充 Flow Layout Panel。 我遇到的问题是同时使用新的 NumbericUpDowns 和新的组合框。以下是我生成 ComboBoxes 和 NumericUpDowns 的方式。

// This int increments each time the code is run. It's located outside of the method below.
int captchaID = 0;

.

// Textboxes that are only for the UI, no code interaction based on text input.
string textboxText = "captchaTextbox";
TextBox newTextbox = new TextBox();
newTextbox.Name = captchaID.ToString() + textboxText;
newTextbox.Text = "";
newTextbox.Width = 175;
itemFlowPanel.Controls.Add(newTextbox);


// Combo Boxes
string comboBoxText = "captchaComboBox";
ComboBox newComboBox = new ComboBox();
newComboBox.Name = captchaID.ToString() + comboBoxText;
newComboBox.Width = 50;
newComboBox.DropDownStyle = ComboBoxStyle.DropDownList;
itemFlowPanel.Controls.Add(newComboBox);

// This array holds my strings that are added to each ComboBox
string[] skills = new string[6];
skills[0] = "STR";
skills[1] = "DEX";
skills[2] = "CON";
skills[3] = "INT";
skills[4] = "WIS";
skills[5] = "CHA";

// This for loop is just populating my ComboBox with the array.
for (int i = 0; i < skills.Length; i++)
{
    newComboBox.Items.Add(skills[i]);
}

// Numeric Up Downs
string numericUpDownText = "captchaNumericUpDown";
NumericUpDown newNumericUpDown = new NumericUpDown();
newNumericUpDown.Name = captchaID.ToString() + numericUpDownText;
newNumericUpDown.Width = 50;
newNumericUpDown.ValueChanged += new EventHandler(captchaNumericUpDown_Click);
newNumericUpDown.ValueChanged += new EventHandler(captchaNumericUpDown_ValueChanged);
itemFlowPanel.Controls.Add(newNumericUpDown);
captchaID++;

使用当前代码,我可以编辑每个 NumericUpDown 包含的事件处理程序,但我还没有找到一种方法让它能够读取它对应的组合框(与验证码一起递增)。

我希望能够为每个事件创建一个新的唯一事件,但如果这不可能,检查组合框 ID 的方法也会有所帮助。

您可以重写 captchaNumericUpDown_ 事件以将 ComboBox 作为附加参数,然后像这样调用它们:

newNumericUpDown.ValueChanged += (sender, args) =>
{
    captchaNumericUpDown_Click(sender, args, newComboBox);
}

以下是快速解决方案:

1) 通过使用字典

Dictionary<NumericUpDown, ComboBox> _controls = new Dictionary<NumericUpDown, ComboBox>();

    // when you create comboBox - add entry with associated numericUpDown
    _controls.Add(numericUpDown1, comboBox1);

// now in the numericUpDown event you can get combobox like this
void numericUpDown_Whatever(object sender, WhateverEventArgs e)
{
    var numericUpDown = (NumericUpDown)sender;
    var comboBox = _controls[numericUpDown];
    // do something
    var selectedIndex = comboBox.SelectedIndex;
    ...
}

2) 通过使用 Tag

    // add combobox into numericUpDown Tag when you create them
    numericUpDown1.Tag = comboBox1;

// now in the numericUpDown event you can get combobox like this
void numericUpDown_Whatever(object sender, WhateverEventArgs e)
{
    var numericUpDown = (NumericUpDown)sender;
    var comboBox = (CombBox)numericUpDown.Tag;
    // do something
    var selectedIndex = comboBox.SelectedIndex;
    ...
}