Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# how do i access my form controls from my class?

Tags:

c#

.net

I have a class in the same namespace as my form. Is it possible for me to access methods/properties of my form controls from my class? How can I accomplish this?

like image 403
Alex Gordon Avatar asked Jan 25 '26 00:01

Alex Gordon


2 Answers

You need to make your controls public, however I wouldn't do that. I'd rather expose just what I need from my controls. So say if I needed access to the text in a text box:

public class Form1 : Form
{
   public string TextBoxText
   {
      get{return this.textBox1.Text;}
      set{this.textBox1.Text = value;}
   }
}
like image 71
BFree Avatar answered Jan 26 '26 16:01

BFree


One way is to pass the form into the class like so:

class MyClass
{
     public void ProcessForm(Form myForm)
     {
           myForm.....; // You can access it here
     }

}

and expose the Controls that you want so that you can access them but really you should pass only what you need to the class, instead of the whole form itself

like image 31
Iain Ward Avatar answered Jan 26 '26 16:01

Iain Ward