Nat
Nat

Reputation: 908

How to modify controls from a different form in C#

Is there a way to modify the text in a textbox, or something like that from a different form?

In my program, I need to spawn a new Form2, and have all the textboxes hold information based on stuff entered in Form3. So far I've only done:

Form2 form2 = new Form2();
form2.Show();

I just don't know how to access form2.textbox1.Text, for example, from form3. I've looked online but didn't find quite what I was looking for, and I've tried a few different things with no success.

Thanks! :)

Upvotes: 0

Views: 67

Answers (3)

ImGreg
ImGreg

Reputation: 2983

Assuming that you are instantiating the Form2 within the code behind of Form3 (calling "new" Form2())...

You can create a public method within Form2 that will provide the accessibility you need. Example:

(within Form2 - code behind)

public SetTextboxTextProperty(string text)
{
    this.Textbox1.Text = text;
}

From Form3:

Form2 form2 = new Form2();
form2.SetTextboxTextProperty("your data");
form2.Show();

Upvotes: 1

Robert
Robert

Reputation: 77

The problem is that the controls defined in each form are not public objects, so you can't access them from outside the form.

Why don't you define a public method in each form to retrieve/set the value you need from the controls you need?

I think that it would be a better approach than exposing your controls.

Upvotes: 1

Mike Perrenoud
Mike Perrenoud

Reputation: 67898

Pass the instance of Form2 into Form3:

public Form3(Form2 referrer)
{
    var txt = referrer.TextBox1Text;
}

and then when calling it:

Form3 f3 = new Form3(this);
f3.Show();

and you'll just have to make sure that you build a property on Form2 like this:

internal string TextBox1Text { get { return textBox1.Text; } }

Upvotes: 2

Related Questions