| View previous topic :: View next topic |
| Author |
Message |
ssaccount Master Cheater
Reputation: 0
Joined: 29 Aug 2007 Posts: 391 Location: Finland
|
Posted: Sat May 03, 2008 12:24 pm Post subject: [C#] Help with global variables |
|
|
I have little problem.
I have form1 and form2. There is label in form1 and label in form2
and in form1 there is button which opens form2.
My problem is that when the form2 opens i want its label get same value as form1's label.
So how am i supposed to do that?
_________________
Programming in C++
(Or at least trying to ) |
|
| Back to top |
|
 |
Stylo Grandmaster Cheater Supreme
Reputation: 3
Joined: 16 May 2007 Posts: 1073 Location: Israel
|
Posted: Sat May 03, 2008 1:36 pm Post subject: |
|
|
okay so first of all you need to make the label at form1 public
lets say that form1 is "Main"
what you do in form2_load is:
| Code: |
private void form2_load(object sender, EventArgs e)
{
Main MainForm = new Main();
label2.text = MainForm.label1.text;
}
|
this should work fine
_________________
Stylo |
|
| Back to top |
|
 |
killersamurai Expert Cheater
Reputation: 0
Joined: 10 Sep 2007 Posts: 197 Location: Colorado
|
Posted: Sat May 03, 2008 1:39 pm Post subject: |
|
|
If you view the code for Form2, you should see
| Code: |
public Form2()
{
InitializeComponent();
}
|
Change it to
| Code: |
Form1 frm1;
public Form2(Form1 temp)
{
frm1 = temp;
InitializeComponent();
}
|
Now, you can get the information. But you have to set the label of form1 to public. Or, you can create a public function to return what is on the label.
| Code: |
public string GetLabel()
{
return label1.Text;
}
|
This is how you would open up form2
| Code: |
Form2 frm2 = new Form2(this);
|
|
|
| Back to top |
|
 |
ssaccount Master Cheater
Reputation: 0
Joined: 29 Aug 2007 Posts: 391 Location: Finland
|
Posted: Sat May 03, 2008 1:43 pm Post subject: |
|
|
Thx it's working now
_________________
Programming in C++
(Or at least trying to ) |
|
| Back to top |
|
 |
samuri25404 Grandmaster Cheater
Reputation: 7
Joined: 04 May 2007 Posts: 955 Location: Why do you care?
|
Posted: Mon May 05, 2008 8:32 pm Post subject: |
|
|
| killersamurai wrote: | If you view the code for Form2, you should see
| Code: |
public Form2()
{
InitializeComponent();
}
|
Change it to
| Code: |
Form1 frm1;
public Form2(Form1 temp)
{
frm1 = temp;
InitializeComponent();
}
|
Now, you can get the information. But you have to set the label of form1 to public. Or, you can create a public function to return what is on the label.
| Code: |
public string GetLabel()
{
return label1.Text;
}
|
This is how you would open up form2
| Code: |
Form2 frm2 = new Form2(this);
|
|
I agree with your idea of using the constructor, but I'd have done it differently:
| Code: |
public Form2(string sLabelText)
{
myLabel.Text = sLabelText;
InitializeComponent();
}
|
Then, when creating the form, just do
| Code: |
Form2 newForm = new Form2(myLabel.Text);
newForm.Show();
|
_________________
|
|
| Back to top |
|
 |
|