Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to access Winforms control in a class

Tags:

c#

winforms

I am currently working in a small windows forms project in C# using Visual studio 2008. I have added a custom class to the project, but in this class I am unable to access the forms controls (like listbox, textbox, buttons ) in order to programmatically change their properties.

The class file has using system.windows.forms included and all files are in the same namespace. Surprisingly, I am also unable to access the controls in the form1 class itself, unless I create a method in the class and then intellisense pops up the names of the various controls.

in the custom class however, intellisense does not show the names of the controls at all.

Appreciate if someone coudl shed some light on why this could be happening.

Thanks

like image 665
dezkev Avatar asked Dec 30 '22 02:12

dezkev


2 Answers

Encapsulation means your separate class shouldn't be talking directly to the controls. You should, instead, expose properties and methods on your (outer) Control - for example:

public string TitleText {
    get {return titleLbl.Text;}
    set {titleLbl.Text = value;}
}

For more complex operations it may be preferable to use a method; properties are fine for simple read/write for discreet values.

This provides various advantages:

  • you can, if required, abstract the details to an interface (or similar)
  • you can change the implementation (for example, use the Form's Text for the title) without changing the calling code
  • it is just... nicer ;-p
like image 98
Marc Gravell Avatar answered Jan 01 '23 17:01

Marc Gravell


Your class needs a reference to the form for this to work. The reason for this is that the form is not a static class so you can have multiple instances of it.

The best way of giving it the reference would probably be to pass it in the classes constructor. Then the class would have a reference to the form and could use that reference to change the controls.

An alternative option that you could use if you are 100% sure that you will have only one instance of your form open is to add a public static property to the forms class that returns the instance of the form. That property would then be available to be used in your other class.

Also, make sure that your controls are public, or better add public methods to your form that can be used to manipulate the controls indirectly.

like image 44
Rune Grimstad Avatar answered Jan 01 '23 17:01

Rune Grimstad