Search code examples
c#visual-studiowinformsdynamicobject

c# using dynamic tools


in c# form application, when i click the button i create a listBox. and I add Item to the ListBox from a TextBox

When I click the button, I want the listBox to be created if it does not exist.

Therefore when assigning the ListBox creation code to an if block, the code to assign the data in the textBox to the listBox fails. how can i fix this?

if (araclar_eklendi == false)
{
ListBox listB_X = new ListBox();
listB_X.******** = new Point(380, 45);
this.Controls.Add(listB_X);

araclar_eklendi=true;
}

listB_X.Items.Add(txtBox_X.text);

Solution

  • You can use foreach statement to traverse the form's Controls to check if a ListBox exists. And define a boolean to store the result.

    Here is a demo you can refer to.

    // bool to check if a listbox exists
    bool flag = false;
    
    private void button1_Click(object sender, EventArgs e)
    {
        Control control = new Control();
        // traverse the form
        foreach (Control c in this.Controls)
        {
            if (c is ListBox)
            {
                control = c;
                flag = true;
                break;
            }
        }
        if (flag) // if true, access the listbox and add new item from tb
        {
            ((ListBox)control).Items.Add(textBox1.Text);
        }
        else // if false, create a new listbox
        {
            ListBox listBox = new ListBox();
            listBox.Location = new Point(380, 45);
            this.Controls.Add(listBox);
            listBox.Items.Add(textBox1.Text);
        }
    }