Your code has only 7 lines but still a rather large number of issues.
Let's see:
You need to be clear and precise! A dumb machine will have to follow your instructions.. Here seven fellow SO members hace tried to guess what you want to do and more or less failed!
You should partition your code into small functions with clear names and little or no dependencies among each other.
This will (hopefully) lead to reusable code..
You should not code any serious logic into events. Instead only a few checks and calling functional methods is recommened.
You seem to want to generate pairs of random numbers and display them in two Labels.
So I start by deciding whether the generation and the display should go into separate functions. For any but the most trivial problems this should definitely be the case. It is called Model-View
separation. But our situation is simple enough to lump them into one function:
void MakeAndShowRandomPair()
We can call it on each click of your button:
private void button1_Click(object sender, EventArgs e)
{
MakeAndShowRandomPair();
}
Now for the genaration of random numbers. The random number genarator object has two constructors, one with a seed
you can choose to control where the sequence should start; this creates a repeatable sequence. The other, without a parameter, uses the current time as its seed. One common mistake is to generate Random object so fast that they are created with the same timestamp as theirs seeds. Those wil always generate the same numbers..
So we genrate it only once at class level:
public Form1()
{
InitializeComponent();
}
Random rand = new Random();
Now for the function itself. You want the numbers to ascend. The are two ways to achieve that:
- Either store the last one and repeatedly generate one until the new one is larger than the old one.
- Or add a random step
I decide to use the latter approach so I need a few variables:
int r1 = 0;
int r2 = 0;
int step1 = 10;
int step2 = 287;
void MakeAndShowRandomPair()
{
// increase by random steps but at least 1:
r1 += rand.Next(step1) + 1;
r2 += rand.Next(step2) + 1;
// display
label1.Text = r1.ToString();
label2.Text = r2.ToString();
}
Note that the variable names are way too short for longer programms! For anything but such a tiny little problem longer and expressive names are obligatory!
Now each click should fill each Label
with a larger number.
But maybe some of the commentators were right and you actually want to make this happen automatically?
In that case the button would start (and maybe stop) a Timer
and in the Timer.Tick
event, guess what - You would call the very same function MakeAndShowRandomPair
! So already we see the benefits of reusable code..