Hi
When working with a Random class, it's a good idea to have only one and to seed it with the current time.
Then what you're doing when you click the button is to reassign your random variables, which is why they change.
Ok, so get your logics out of your frontend and get your frontend with proper naming. I mean Form1, button1, really? and even on the code project. Let me encourage you to grow out of that fast :)
So let's invent a manger object for your random handling and a set for matching!
But first verify your input, to produce readable code which doesn't have odd errors.
private int GetValidInputOrThrow(TextBox textbox)
{
if (string.IsNullOrEmpty(textbox.Text) || textbox.Text.Length != 1)
throw new ArgumentException("Only one number in each box, please", "textbox");
return int.Parse(textbox.Text);
}
private void button1_Click(object sender, EventArgs e)
{
int one = GetValidInputOrThrow(textBox1);
int two = GetValidInputOrThrow(textBox2);
int three = GetValidInputOrThrow(textBox3);
int four = GetValidInputOrThrow(textBox4);
MatchSet matchThis = MatchManager.GetMatchSet();
if (one.Equals(matchThis.NumberOne))
TextBox1.Backcolor = Color.LightGreen;
Now for the matchmanager class which essentially wraps an matchset and enables that to be reset using getnewmatchset, should you want that option as well.
public class RandomMatchManager
{
private Random _rnd = new Random((int)DateTime.Now.Ticks);
private MatchSet _matchSet;
public MatchSet GetNewMatchSet()
{
_matchSet = new MatchSet
{
NumberOne = _rnd.Next(0, 9),
NumberTwo = _rnd.Next(0, 9),
NumberThree = _rnd.Next(0, 9),
NumberFour = _rnd.Next(0, 9)
};
return _matchSet;
}
public MatchSet GetMatchSet()
{
if (_matchSet == null)
return GetNewMatchSet();
return _matchSet;
}
}
public class MatchSet : IEquatable<MatchSet>
{
public int NumberOne { get; set; }
public int NumberTwo { get; set; }
public int NumberThree { get; set; }
public int NumberFour { get; set; }
public bool Equals(MatchSet other)
{
return NumberOne.Equals(other.NumberOne) && NumberTwo.Equals(other.NumberTwo) && NumberThree.Equals(other.NumberThree) && NumberFour.Equals(other.NumberFour);
}
}
You will notice that the Random is kept and that the matchset offers the ability to compare the entire set, the individual values have the same from being value types. The Random is newed up with the current time tick value, to avoid getting the same values series as random really isn't necessarily that random :)
And so last bit unrevealed is making a lazy property on the form of the manager type
public partial class Form1 : Form
{
private RandomMatchManager MatchManager
{
get
{
if (_matchManager == null)
_matchManager = new RandomMatchManager();
return _matchManager;
}
}
private RandomMatchManager _matchManager;