Reaching parent form controls properties from child form?

G

Guest

Hi,

I have Form1 with a TextBox control on it and I have Form2 that I am showing
from Form1.

private void btnShowForm2_Click(object sender, EventArgs e)
{
Form2 objForm2 = new Form2();
objForm2.ShowDialog();
}

What I would to do is to change the TextBox text property on Form1 from
Form2 like for example something like that:

Form1.txtTextBox1.Text = "abc";

In other words, how can I rich the controls on the parent form?


Thanks in advanced for any help.
Asaf
 
T

Trevor Braun

Asaf,
You can do one of two things:
First, and easiest, is to go to the form designer of Form1, and change the
text box's Modifier attribute to internal or public. Then you would use the
following code in Form2 to reach Form1's text box:
((Form1)this.ParentForm).txtTextBox1.Text = "abc";

Secondly, you can expose the text property only of Form1's textbox via an
internal or public property. In Form1 add the following:

public string TextBox1Text // or something more explanatory
{
get { return txtTextBox1.Text; }
set { txtTextBox1.Text = value; }
}

Then in Form2 you would access the text box value using
((Form1)this.ParentForm).TextBox1Text = "abc";

The second method just provides more protection to your form1 textbox. Only
the text of the textbox can be changed and no other properties can be
changed accidentally. This is the method I recommend.

Trevor B
 
G

Guest

Hello Trevor,

I found the solution for SDI forms.

In Form1:

private void btnShowForm2_Click(object sender, EventArgs e)
{
Form2 objForm2 = new Form2();
objForm2.ShowDialog(this); //Create Handle for Form1
}


In Form2:

private void btnForm2_Click(object sender, EventArgs e)
{
((Form1)this.Owner).txtForm1.Text = "aaa";
}

Thanks for your help & time.

Regards,
Asaf
 
G

Guest

Hello Trevor,

When using this code ((Form1)this.ParentForm).txtForm1.Text = "aaa"; from
Form2 I am receiving the error "Object reference not set to an instance of an
object."

Regards,
Asaf
 
G

Guest

Hello Trevor,

I am using two SDI forms not MDI as your solution is good only for MDI forms.

Regards,
Asaf
 
T

Trevor Braun

Not really a big issue Asaf. The solution I presented is not for MDI forms,
but does assume that Form2 is owned by Form1.
The change you need to make (and has nothing to do with MDI) is:
change
objForm2.ShowDialog();
to
objForm2.ShowDialog(objForm1);

HTH
Trevor
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top