I have a small game, this game have 5 diferent window forms, each window have diferent designs.
First: Welcome page, with play and rules Second: Level choice third: Actuall game fourth: Store to buy gadgets
I use this to open the new window and close the previous one
FormMain formMain = new FormMain();
formMain.Show();
this.Hide();
}
How can I pass variables to the new page, in both cases, the form sending and the form receiving. I tried this
formMain.Show(x, y);
But the show class implies other stuff.
My point is:
1 - depending on the label shosen with the level (1, 2, 3, 4, 5), I pass diferent values to the enemies, so I don´t have to create one form to each level.
2 - Choosing gadgets in the store passes to the game form to increase the player win.
CodePudding user response:
There are tons of options but ill list a few:
1 passing data via the constructor of the Form/Class
public ClassName(int var1, int var2)
{
//do something with var1 and var2
}
this might not be the best option if you want to do some animation with the passed data.
2 setting public variables after the class were created
public class ClassName()
{
public int var1, var2;
}
elsewhere in code
ClassName clObject = new ClassName();
clObject.var1 = 1;
clObject.var2 = 2;
clObject.Show();
3 calling a method to pass the data
public class ClassName()
{
private int var1, var2;
public void DoTheThing(int var1, int var2)
{
//do something with the data
}
}
elsewhere in code
ClassName clObject = new ClassName();
clObject.Show();
clObject.DoTheThing(1,2);
CodePudding user response:
You can create an instance of the second form and access the public methods easily. I leave an example below.
// Click Event On First(Main) Form
private void ParameterSelect_Click(object? sender, EventArgs e)
{
try
{
string value = "Test";
var secondFormInstance = new SecondForm();
var result = secondFormInstance.SwitchExampleMethod(value);
if (result != null)
{
Console.WriteLine($"{result}");
}
}
}
catch (Exception ex)
{
Log.Error($"Error while click event. Error: {ex.Message}");
}
}
// Second Form Method
public string SwitchExampleMethod(string value)
{
try
{
switch (value)
{
case "Test":
case "Test1":
case "Test2":
case "Test3":
return "This value string for just a Test.";
case "Insane":
case "Wow":
return "This is amazing string text.";
default:
return "This is default string text.";
}
}
catch (Exception ex)
{
Log.Error($"Error on switch. Error : {ex.Message}");
return $"Error on switch. Error : {ex.Message}";
}
}