tags:

views:

1005

answers:

5

Hello,

I have a method that executes inside one form, but I need to retrieve data from another form to pass into the method.

Whats the best way of doing this?

+1  A: 

You can expose a property on one form and call it from the other. Of course you'll need some way of getting the instance of form1. You could keep it as a static property in the program class or some other parent class. Usually in this case I have a static application class that holds the instance.

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

Then when you launch the first form, set the application MyFormInstance property to the instance of the first Form.

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

Add a 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
Joshua Belden
Okay, an easier way would be to mark the Modifier property of the textbox as Public, then you could access it directly but you'll still need a way to get to the instance.
Joshua Belden
+1  A: 

On the form that has the textbox you need data from, expose either a Property or a Method that returns the text. IE:

internal string TextBoxTest
{
   get{ return this.textBox1.Text;}
}
BFree
so how do i call that method from the form that i want to execute my original method in?
Goober
A: 

Don't do this.

Longer version: Why is your view directly interacting with another view?

Much longer version:

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

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

Tetsujin no Oni
+1  A: 

There is a similar post here

The videos below will clear up a lot of your concepts about passing data between 2 forms.

There are multiple ways to pass data between 2 forms check these links which has example videos to do this

HTH

Suneet
A: 

Assuming that formB is initialized in formA I would recommend adding a string to the constructor of formB sending the Texbox1.Text

as in

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

}
vaquito