I have a label called LabelX1. This is on form2. On form1, i have a button. I want the button\'s text to be transferred to the other form\'s label. I have tried
<
the only think you have to do is to put the label of the other form as public
for instance: Form1:
public System.Windows.Forms.Label txtInfo;
then in Form2
Form1 frm =new Form1();
frm.txtInfo.text="....."//you have access because is public
form2 frm2 = new form2();
((Label)frm2.Controls["labelX1"]).Text=button1.Text;
frm2.Show();
You could modify the constructor of Form2 like this:
public Form2(string labelText)
{
InitializeComponent();
this.labelX1.Text = labelText;
}
then create Form2 passing in the text:
Form2 frm2 = new Form2(this.button1.text);
If you are needing to access the form2 from elsewhere in your code (like a button press for instance) you will not be able to see the instance of the form you create. To solve that I create a public instance to hold a reference to it like:
public form2 form2_pub;
Then after you create it you assign the new one to your public instance:
form2 frm2 = new form2();
frm2.Show();
form2_pub = frm2
Now you can reference form2_pub throughout your routines.
Works for me at least.
Remember, in your setter you can run whatever other code you want. For instance, I use the following to show what I want on another form by just setting show_scanning to true:
public bool show_scanning //turns on the scanning screen
{
set
{
scanning_pnl.Visible = true;
notReady_pnl.Visible = false;
timer1.Enabled = true;
}
}
inside form2 write this
public void ChangeLabel(string s)
{
labelX1.Text = s;
}
then where you create Form 2 do this
form2 frm2 = new form2();
frm2.ChangeLabel(this.button1.text);
Is there an easy, straight forward way of doing this?
Easiest way is to make labelX1 a public member of form2. The issue you're having is because from Form1 code form2.labelX1 isn't visible. In form2 designer you can go to properties of labelX1 and set it's visibility to public/internal.
Better approach would be to expose labelX1.Text as a property which can be set in code outside the class.