【问题标题】:WinForms - Dynamically create textbox based on ComboBox selectionWinForms - 基于 ComboBox 选择动态创建文本框
【发布时间】:2020-05-06 05:58:09
【问题描述】:

我正在尝试根据以下步骤动态地根据ComboBox 上的选择创建TextBox

第一步(从ComboBox中选择一个来源):

第二步(Textbox应该基于ComboBox.SelectedValue出现):

最后一步(新的ComboBox 应该出现在下面):

我使用以下代码创建了一个createTextBox 函数:

public void createTextBox(int numPassenger)
{
    TextBox[] passengerBoxes = new TextBox[numPassenger];

    for (int u = 0; u < passengerBoxes.Count(); u++)
    {
        passengerBoxes[u] = new TextBox();
    }
    int i = 0;
    foreach (TextBox txt in passengerBoxes)
    {
        string name = "passenger" + i.ToString();

        txt.Name = name;
        txt.Text = name;
        txt.Location = new Point(244, 32 + (i * 28));
        txt.Visible = true;
        this.Controls.Add(txt);
        i++;
    }
}

有没有办法可以修改我当前的功能以适应上述步骤?另外,如何找到动态创建的TextBox

【问题讨论】:

  • 在 combobox_selection_changed 事件中,您必须调用创建文本框的方法。该方法应该循环遍历所有控件并找到已选择值的组合框。对于这些中的每一个,都应该创建一个文本框。 this.Controls 包含 winform 上的所有控件。您可以遍历列表。
  • 谁想到使用组合框来选择您要编辑的内容?为什么不使用标准表单,您可以在其中查看和编辑所有内容?
  • 最好事先创建控件并根据您的选择显示/隐藏。

标签: c# winforms combobox textbox


【解决方案1】:

你可以试试下面的代码:

    private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        createTextBox(sender as ComboBox);
    }
    private void createTextBox(ComboBox cmb)
    {
        TextBox passengerBoxes = new TextBox();
        string name = cmb.Text;
        if (Controls.Find(name, true).Length == 0)
        {
            passengerBoxes.Name = name;
            passengerBoxes.Text = name;
            int textBoxCount = GetTextBoxCount();
            passengerBoxes.Location = new Point(244, 32 + (textBoxCount * 28));
            passengerBoxes.Visible = true;
            this.Controls.Add(passengerBoxes);

            if (cmb.Items.Count != 1)//last item remaining then we should not create new combo box
            {
                ComboBox newCombo = new ComboBox
                {
                    Location = new Point(cmb.Location.X, 32 + ((textBoxCount + 1) * 28))
                };

                foreach (string str in cmb.Items)
                    if (cmb.Text != str)
                        newCombo.Items.Add(str);

                newCombo.SelectedIndexChanged += comboBox1_SelectedIndexChanged;

                this.Controls.Add(newCombo);
            }
        }
        else
            MessageBox.Show("Textbox Already for the selected source " + name);
    }

    private int GetTextBoxCount()
    {
        int i = 0;
        foreach (Control ctl in this.Controls)
        {
            if (ctl is TextBox) i++;
        }
        return i;
    }

【讨论】:

    猜你喜欢
    • 2019-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-07
    • 1970-01-01
    • 1970-01-01
    • 2020-06-18
    相关资源
    最近更新 更多