[c#] 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?

This question is related to c# winforms class inheritance controls

The answer is


I was also facing the same problem where I was not able to appendText to richTextBox of Form class. So I created a method called update, where I used to pass a message from Class1.

class: Form1.cs

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            _Form1 = this;
        }
        public static Form1 _Form1;

        public void update(string message)
        {
            textBox1.Text = message;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Class1 sample = new Class1();            
        }
    }

class: Class1.cs

public class Class1
    {        
        public Class1()
        {
            Form1._Form1.update("change text");
        }        
    }

// Take the Active form to a form variable.

Form F1 = myForm1.ActiveForm;

//Findout the Conntrol and Change the properties

F1.Controls.Find("Textbox1", true).ElementAt(0).Text= "Whatever you want to write";


I used this method for updating a label but you could easily change it to a textbox:

Class:

public Class1
{
    public Form_Class formToOutput;

    public Class1(Form_Class f){
        formToOutput = f;
    }

    // Then call this method and pass whatever string
    private void Write(string s)
    {
        formToOutput.MethodToBeCalledByClass(s);
    }
}

Form methods that will do the updating:

public Form_Class{

    // Methods that will do the updating
    public void MethodToBeCalledByClass(string messageToSend)
    {
       if (InvokeRequired) { 
           Invoke(new OutputDelegate(UpdateText),messageToSend); 
       }
    }

    public delegate void OutputDelegate(string messageToSend);
    public void UpdateText(string messageToSend)
    {
       label1.Text = messageToSend;
    }
}

Finally

Just pass the form through the constructor:

Class1 c = new Class1(this);

public partial class Form1 : Form
{

    public static Form1 gui;
    public Form1()
    {
        InitializeComponent();
        gui = this;

    }
    public void WriteLog(string log)
    {
        this.Invoke(new Action(() => { txtbx_test1.Text += log; }));

    }
}
public class SomeAnotherClass
{
    public void Test()
    {
        Form1.gui.WriteLog("1234");
    }
}

I like this solution.


If your other class inherits Form1 and if your textBox1 is declared public, then you can access that text box from your other class by simply calling:

otherClassInstance.textBox1.Text = "hello world";

Form1 form = new Form1(); 
form.textBox1.Text = "test";

I Found an easy way to do this,I've tested it,it works Properly. First I created a Windows Project,on the form I Inserted a TextBox and I named it textBox1 then I inserted a button named button1,then add a class named class1. in the class1 I created a TextBox:

class class1
    {
     public static TextBox txt1=new TextBox();  //a global textbox to interfece with      form1
    public static void Hello()
      {
       txt1.Text="Hello";
      }
    }

Now in your Form Do this:

public partial class Form1 : Form
    {
     public Form1()
     {
      InitializeComponent();  
     }
     private void button1_Click(object sender, EventArgs e)
      {
       class1.txt1=textBox1;
       class1.Hello();
       }
    }

in the button1_Click I coppied the object textBox1 into txt1,so now txt1 has the properties of textBox1 and u can change textBox1 text in another form or class.


Form frm1 = new Form1();
frm1.Controls.Find("control_name",true)[0].Text = "I changed this from another form";

Define a property of the form like, then use this in other places it would be available with the form instance

public string SetText
{
  get { return textBox1.Text; }
  set { textBox1.Text = value; }
}

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

}

You will need to have some access to the Form's Instance to access its Controls collection and thereby changing the Text Box's Text.

One of ways could be that You can have a Your Form's Instance Available as Public or More better Create a new Constructor For your Second Form and have it receive the Form1's instance during initialization.


Use, a global variable or property for assigning the value to the textbox, give the value for the variable in another class and assign it to the textbox.text in form class.


What about

Form1.textBox1.text = "change text";

note: 1. you have to "include" Form1 to your second form source file by using Form1;

  1. textBox1 should be public

You can change the access modifier for the generated field in Form1.Designer.cs from private to public. Change this

private System.Windows.Forms.TextBox textBox1;

by this

public System.Windows.Forms.TextBox textBox1;

You can now handle it using a reference of the form Form1.textBox1.

Visual Studio will not overwrite this if you make any changes to the control properties, unless you delete it and recreate it.

You can also chane it from the UI if you are not confortable with editing code directly. Look for the Modifiers property:

Modifiers


I tried the examples above, but none worked as described. However, I have a solution that is combined from some of the examples:

public static Form1 gui;
public Form1()
{
    InitializeComponent();
    gui = this;
    comms = new Comms();

}
public Comms()
{
    Form1.gui.tsStatus.Text = "test";
    Form1.gui.addLogLine("Hello from Comms class");
    Form1.gui.bn_connect.Text = "Comms";
}

This works so long as you're not using threads. Using threads would require more code and was not needed for my task.


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to winforms

How to set combobox default value? Get the cell value of a GridView row Getting the first and last day of a month, using a given DateTime object Check if a record exists in the database Delete a row in DataGridView Control in VB.NET How to make picturebox transparent? Set default format of datetimepicker as dd-MM-yyyy Changing datagridview cell color based on condition C# Inserting Data from a form into an access Database How to use ConfigurationManager

Examples related to class

String method cannot be found in a main class method Class constructor type in typescript? ReactJS - Call One Component Method From Another Component How do I declare a model class in my Angular 2 component using TypeScript? When to use Interface and Model in TypeScript / Angular Swift Error: Editor placeholder in source file Declaring static constants in ES6 classes? Creating a static class with no instances In R, dealing with Error: ggplot2 doesn't know how to deal with data of class numeric Static vs class functions/variables in Swift classes?

Examples related to inheritance

How to extend / inherit components? Inheritance with base class constructor with parameters Class is not abstract and does not override abstract method Why not inherit from List<T>? Can an interface extend multiple interfaces in Java? How to call Base Class's __init__ method from the child class? How should I have explained the difference between an Interface and an Abstract class? JavaScript OOP in NodeJS: how? When do I have to use interfaces instead of abstract classes? C++ calling base class constructors

Examples related to controls

What is Dependency Injection and Inversion of Control in Spring Framework? Change the location of an object programmatically How to access Winform textbox control from another class? How to make overlay control above all other controls? How to get ALL child controls of a Windows Forms form of a specific type (Button/Textbox)? How can I change the Java Runtime Version on Windows (7)? How can I make visible an invisible control with jquery? (hide and show not work) DataGridView - how to set column width? Get a Windows Forms control by name in C# C# Get a control's position on a form