accesing Form1:controls from other class

  • Thread starter Thread starter user
  • Start date Start date
U

user

Hello
I have Form1 : System.Windows.Forms.Form and some public controls in it:
public System.Windows.Forms.ComboBox comboBox1;
public System.Windows.Forms.ComboBox comboBox2;

in the same project i have some other files with some otherclasses.
Can i access any of theese controls from that other classes ?
How ?


Thanx
 
If you make the controls public, yes. But the other classes would need a
reference to Form1 which you can give to the other classes when creating
them (as a parameter in the constructor).

However, a better way would be to make accessible methods or properties in
Form1 which could update the controls. The other classes would then call
these methods or properties to update the controls instead of handling the
controls directly (better OOP practice to let Form1 handle it's own
controls).
 
If you make the controls public, yes. But the other classes would need
a reference to Form1 which you can give to the other classes when
creating them (as a parameter in the constructor).

However, a better way would be to make accessible methods or properties
in Form1 which could update the controls. The other classes would then
call these methods or properties to update the controls instead of
handling the controls directly (better OOP practice to let Form1 handle
it's own controls).

ok, but after that how do i have acces to Form1 properties/methods ?
i tried:
mynamespace.Form1.???
where should i seek Form1 properties/method ?

Thanx
 
Hi,

If you are sure that will create only one instance of Form1 then you can
keep a reference to the instance on a static variable:

class Form1{
public static Form1 Instance;

public Form1()
{
Instance = this;
}
}

Then you can use F.Instance from anywhere in your application without need
to pass a reference.

Hope this help,
 
You need to pass a reference to Form1 to your class when creating it.

public class Form1 : System.Windows.Forms.Form
{
private Class1;
public ComboBox ComboBox1;

public string ComboText
{
get
{
return ComboBox1.Text;
}
set
{
if(value.Length <= 15)
ComboBox1.Text = value;
}
}

public Form1()
{
Class1 = new Class1(this);
}

public void ChangeValues()
{
ComboBox1.Text = "Text Sample 2";
}
}

public class Class1
{
private Parent;

public Class1(Form1 f)
{
Parent = f;
}

private void SomeMethod()
{
Parent.ComboBox1.Text = "Text Sample 1";
Parent.ChangeValues();
Parent.ComboText = "Text Sample 3";
}
}

Happy coding!
Morten
 
Back
Top