简体   繁体   中英

How to access a listBox from another windows form in Visual Studio?

I have two forms in my project. One is named formOptions and another is formHome. I have a listBox in formOption named Blacklist. I have a textBox by which I can add text to the "Blacklist" listBox. Now, I want to access the items from "Blacklist" listBox from formHome. I have tried the following approach:

private void formHome_Load(object sender, EventArgs e)
{
    formOptions.Blacklist // as follows 
}

But at this point it shows an error that "An object reference is required for the non-static field, method, or property 'formOptions.Blacklist'.

Now, What can I do to access the listBox?

You can see here how to make instance of a form (fromOpition) on formHome.

By studying this example code, you can get help:

//this code written in form1
Form2 form2 = new Form2();  //Form2 is my second Form
foreach(Control control in form2.Controls)
{
    if(control.GetType()==typeof(ListBox))  //you can put any typeof object
    {
        ((ListBox)control).Items.Add("HELLO"); 
        break;
    }
}
form2.ShowDialog();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM