I am making a quick application which displays a random number onto a second windows Form. I am making it as a random number generator as when the random number is displayed from the click button event handler. I am having trouble figuring out how to display my random generated number onto my new windows Form. I have created two Forms. Here is my code below:
{
public partial class Form1 : Form
{
Random rnd = new Random();
int randomnumber;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
randomnumber = rnd.Next(100);
Form2 r2 = new Form2();
r2.ShowDialog();
MessageBox.Show( randomnumber.ToString());
// as you see, I displayed it to a MessageBox because
// I was having difficulty showing this value onto the second windows forum named Form 2
}
}
}
// note, this is the code for the first form.
and below is my code for the second form:
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
this.Close();
}
private void label5_Click(object sender, EventArgs e)
{
}
}
}
Option 01
You can create a method in Form2 that would assign the value to desired Label control.
public void AssignRandomNumber(int randomNumber)
{
label5.Text = randomNumber.ToString();
}
And then after generating the Random Number, you can use the method to assign the value.
randomnumber = rnd.Next(100);
Form2 r2 = new Form2();
r2.AssignRandomNumber(randomnumber);
r2.ShowDialog();
Option 2:
You could do the same with the Constructor of Form2
public Form2(int randomNumber)
{
InitializeComponent();
label1.Text = randomNumber.ToString();
}
In this case, your code in Form1 would look like
randomnumber = rnd.Next(100);
Form2 r2 = new Form2(randomnumber);
r2.ShowDialog();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With