Alex Gordon
Alex Gordon

Reputation: 60691

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

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?

Upvotes: 2

Views: 10097

Answers (4)

Sabbir
Sabbir

Reputation: 1374

You need to generate stubs.

For that

In your custom class write a constructor

public YourClass(Main main)   
{
        // TODO: Complete member initialization
        this.main = main;
}

then in main class/form class, initialize your class

YourClass yesMyClass = YourClass(this);

If your want to access form components on your custom class then,

this.main.label1.Text="I done that smartly'

Upvotes: 0

Iain Ward
Iain Ward

Reputation: 9936

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

Upvotes: 3

BFree
BFree

Reputation: 103742

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;}
   }
}

Upvotes: 10

Simon Fischer
Simon Fischer

Reputation: 3876

If you pass a reference of your form to your class you should be able to access methods and properties of your form from your class:

public class MyClass
{
    private Form form;

    public void GiveForm(Form form)
    {
        this.form = form;
    }
}

Upvotes: 2

Related Questions