Writing text to another form

R

RSH

I have a basic framework where I have a frmMain which is my main form that
is opened when the application is run. Upon a button click I have a second
from that is opened as such:

Form FormB = new Form2();

FormB.Show();

That form has a label called "label1" which I would like to write to from
frmMain. I tried the somewhat logical (but inncorrect) syntax:

FormB.label1.text = "Success!";

Which doesn't work...I get a compile error:

Error 1 'System.Windows.Forms.Form' does not contain a definition for
'label1' \InitialData\Form1.cs 53 19 InitialData

What should I be doing here, and why doesn't this work the way one would
expect?



Thanks!

RSH
 
M

Marc Gravell

Firstly, you've cast FormB as a Form - so you only have access to the
properties of a Form; try changing this to:

Form2 FormB = new Form2();

Second, I doubt that the actual label "label1" is marked as public, so you
probably can't access it directly.

The way to do this would be to add the following to Form2's declaration:

public string LabelText {
get {return label1.Text;}
set {label1.Text = value;}
}

And change your code to put FormB.LabelText = "Success!";

This uses a public property to avoid having to have direct access to a
private member variable.

Let me know if this helps,

Marc
 
C

Chris Dunaway

RSH wrote:

Instead of:
Form FormB = new Form2();

FormB.Show();

Try this:

Form2 FormB = new Form2();
FormB.Show();
FormB.label1.Text = "Success!";
Error 1 'System.Windows.Forms.Form' does not contain a definition for
'label1' \InitialData\Form1.cs 53 19 InitialData

That's because the System.Windows.Forms.Form does not have a label1
property. Your Form2 class does.

If you need to declare FormB as a generic Form then you can cast the
generic form to your form class like this:

Form FormB = new Form2();
FormB.Show();

(Form2) FormB.label1.Text = "Success!";


HTH

Chris
 
D

D. Yates

RSH,

You could also add a new constructor to Form2 that accepts a string, which
you could then assign to the label.

Dave
 

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