Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access Winform textbox control from another class?

I have a winform called Form1 and a textbox called textBox1

In the Form1 I can set the text by typing:

textBox1.text = "change text"; 

Now I have created another class. How do I call textBox1 in this class? so I want to change the text for textBox1 in this class.

How can I access the Form1 from this new class?

like image 740
Psychocryo Avatar asked Apr 13 '11 09:04

Psychocryo


People also ask

How do I add a class in Windows Forms?

Now we start, first we create the Windows Form Based Project then after choosing Windows Form Project we press OK Button. Step 2: After creating the project we add the class and change the name of the class and set the name as Connection Class. Left click on you project and add class and press add button.


1 Answers

I would recommend that you don't. Do you really want to have a class that is dependent on how the text editing is implemented in the form, or do you want a mechanism allowing you to get and set the text?

I would suggest the latter. So in your form, create a property that wraps the Text property of the TextBox control in question:

public string FirstName {     get { return firstNameTextBox.Text; }     set { firstNameTextBox.Text = value; } } 

Next, create some mechanism through which you class can get a reference to the form (through the contructor for instance). Then that class can use the property to access and modify the text:

class SomeClass {     private readonly YourFormClass form;     public SomeClass(YourFormClass form)     {         this.form = form;     }      private void SomeMethodDoingStuffWithText()     {         string firstName = form.FirstName;         form.FirstName = "some name";     } } 

An even better solution would be to define the possible interactions in an interface, and let that interface be the contract between your form and the other class. That way the class is completely decoupled from the form, and can use anyting implementing the interface (which opens the door for far easier testing):

interface IYourForm {     string FirstName { get; set; } } 

In your form class:

class YourFormClass : Form, IYourForm {     // lots of other code here      public string FirstName     {         get { return firstNameTextBox.Text; }         set { firstNameTextBox.Text = value; }     } } 

...and the class:

class SomeClass {     private readonly IYourForm form;     public SomeClass(IYourForm form)     {         this.form = form;     }      // and so on  } 
like image 180
Fredrik Mörk Avatar answered Sep 25 '22 22:09

Fredrik Mörk