C # WinForms - How to get data from a textbox on one form through another form?

I have a method that runs inside one form, but I need to get data from another form to go to the method.

What's the best way to do this?

+1


a source to share


5 answers


Assuming Form B is initialized to Form A, I would recommend adding a line to Form B's constructor by submitting Texbox1.Text

how in



class formB: Form{
   private string data;
   public formB(string data)
    {
        InitializeComponent();
        this.data = data;
    }
  //rest of your code for the class

}

      

0


a source


You can open a property in one form and call it from another. Of course, you need to get an instance of form1 somehow. You can store it as a static property in the program class or another parent class. Usually in this case, I have a static application class that contains an instance.

public static class Application
{
public static MyForm MyFormInstance { get; set; }
}

      

Then, when you run the first form, set the application's MyFormInstance property to an instance of the first form.

MyForm instance = new MyForm();
Application.MyFormInstance = instance;

      



Add the property to the second form.

public String MyText
{ get { return textbox1.Text; }
  set { textbox1.Text = value; }
}

      

And then you can access it from your second form with:

Application.MyFormInstance.MyText

      

+2


a source


On a form that has a text box where you need data, output either a property or a method that returns text. IE:

internal string TextBoxTest
{
   get{ return this.textBox1.Text;}
}

      

+1


a source


There is a similar post here

The videos below will clarify many of your concepts about transferring data between two forms.

There are several ways to pass data between the two forms that check these links, which have video examples for this.

NTN

+1


a source


Do not do that.

Longer version: Why does your view interact directly with another view?

Longer version:

Rather than creating a public property that exposes the field, it would provide better encapsulation and isolation from modification if the form with the field of interest interacted with some kind of data object that was then passed to the interested method.

The location of the method concerned must be carefully considered - if it controls aspects of the view (WinForm, in your case), then it might be a relevant member of that class - if not, perhaps its real home is in the data object?

0


a source







All Articles