how to use Form1 listbox from other class within the same namespace

  • Thread starter Thread starter Robert
  • Start date Start date
R

Robert

Hi

I have an Form1 class generated with studio with an listbox on it.
how can i access this listbox from other classes ?

public class Form1 : System.Windows.Forms.Form
{
public System.Windows.Forms.ListBox listBox1;
private void button1_Click(object sender, System.EventArgs e)
{
listBox1.Items.Add("some text");
}
}

public class ServerClass : MyTestInterface
{
public override string MyFirstMethod(string what)
{
// here i want to add some text to Form1.listbox1


return "" + what;

}

}
 
Robert,

First, you have to expose the listbox, either by making its
accessibility public, or by exposing it through a property of some kind.
Then, you would pass a reference to the form to the class that you want to
use it, by setting a property, or passing it through a method. A form is
like any other object which has properties, methods, and fields. You have
to pass it around to access it.

Hope ths helps.
 
You need to pass the object reference to Form1 when creating ServerClass,
then use Form1.listBox1.Items.Add("more text");

ServerClass newServerClass = new ServerClass(this);

and

private Form1 parent = null;

public ServerClass(Form1 parent)
{
this.parent = parent;
}

There may be other and better ways, but this should work.
 
yes but when the client invokes MyFirstMethod method
an another instance of ServerClass is cretead
where the parent is not set .

there is no choice to use an "global" variable ?


Robert
 
simply declare it as public static. this is usefull when you cannot instance
a form (main form for example).
from time to time, stupid editor will remove static from code, so just add
it back
 
Back
Top