0

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);
  • 1
    This code is run in a Button.Click event, hence the `ListBox listB_X` is a local object: you won't be able to use this reference later (as in `listB_X.Items.Add(txtBox_X.text);`). Declare the ListBox as an instance Field and check if it's `null` to decide whether to create it new or just access it. But you could simply create it and then show it the first time its presence is requested. – Jimi Mar 18 '20 at 22:50
  • If the position and the size etc. of the list box is fixed, why don't you just add it to your form as usual (using the designer) and make it hidden (Visible: false) at first? You can then, in this event handler, make it visible when it needs to be shown, and if it is not visible already. – Oguz Ozgul Mar 18 '20 at 23:00

1 Answers1

0

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);
    }
}
大陸北方網友
  • 3,696
  • 3
  • 12
  • 37