Transferring data between forms
I've got two forms. In the first, I have a textbox and a button, and in the other one I have a label. When you enter text in the textbox, and press button, a new form is opened, and the label has the same text as the textbox in the previous form. How do I do that with get/set? I made a class "Globals", and in it get/set:
class Globals
{
public string imena = "";
public string ime
{
get
{
return imena;
}
set
{
开发者_StackOverflow中文版 imena = value;
}
}
}
and in the first form
private void btnplay_Click(object sender, EventArgs e)
{
//this.Hide();
Game igra = new Game();
igra.Show();
Globals promenljive = new Globals();
promenljive.ime = tbpl1.Text;
}
and in the second one
private void Game_Load(object sender, EventArgs e)
{
Globals promenljive = new Globals();
lblime1.Text = promenljive.ime;
}
But it doesn't work? What did I do wrong?
Well you're creating two separate instances of Globals
, to start with... those will have independent variables, which is why you're not seeing the value you've just set. It's like painting one house red, then looking at the colour of a completely different house.
However, using a "globals" class like this is a bad idea. Why not just add a parameter to the Game
constructor, and pass in the data that way?
Game igra = new Game(tbpl1.Text);
igra.Show();
It sounds like you may be new to OOP given your initial approach. If this is the case, I would strongly advise you to learn about the basics of C#, .NET and OO in general before starting to write GUI applications. GUIs have their own difficulties (such as threading rules) and are hard enough to develop even when you're confident of the basics. At the moment, you'll find it hard to tell the difference between a genuinely GUI-specific problem and simply one of not understanding how C# and .NET work in general.
No. It won't work because you are having two different instances (variables) of Globals. Each with with its different set of values.
You need to use one shared Globals variable between the two forms.
Example:
Create in Form1 the global variable and then, when you instantiate Game, pass the global reference in the constructor:
Globals promenljive = new Globals();
promenljive.ime = tbpl1.Text;
Game igra = new Game(promenljive);
igra.Show();
And then, store the reference in Game's constructor:
public Game(Globals g) {
this.promenljive = g; // you need a global member in Game called promenljive
}
Hope it helps.
You can not create a new Globals in Game_Load, you have to pass a reference to a Globals object into the constructor of Game.
精彩评论