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

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

Post by Rober » Tue, 07 Oct 2003 20:51:43


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;

}

}
 
 
 

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

Post by Nicholas P » Tue, 07 Oct 2003 21:23:44

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.


--
- Nicholas Paldino [.NET/C# MVP]
- nick(dot)paldino=at=exisconsulting<dot>com

 
 
 

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

Post by Morten Wen » Tue, 07 Oct 2003 21:32:09

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.

--
Using M2, Opera's revolutionary e-mail client: http://www.yqcomputer.com/
 
 
 

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

Post by Robert Kal » Wed, 08 Oct 2003 01:03:47


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



*** Sent via Developersdex http://www.yqcomputer.com/ ***
Don't just participate in USENET...get rewarded for it!
 
 
 

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

Post by Andrij » Wed, 08 Oct 2003 05:11:18

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