I am tring to create random drawing colors. There is an error. Could you help me about this code.
private Random random;
private void MainForm_Load(object sender, EventArgs e)
{
random = new Random();
}
private Color GetRandomColor()
{
return Color.FromArgb(random.Next(0, 255), random.Next(0,255),random.Next(0,255));
// The error is here
}
public SolidBrush brushGet()
{
SolidBrush oBrush = new SolidBrush(GetRandomColor());
return oBrush;
}
I don't see any problems with the above code, other than the Random object not being initialized before it is called to. There is also absolutely no need to initialize it in the Load event of the form; it can be done right when it's declared:
private static readonly Random Random = new Random();
Personally I'd not declare it on local scope, as far as I know you end up with the same value every time if you go about it that way. I also personally don't see the need of overcomplicating things; generating random numbers everytime and using the Color.FromAgb()
method you should be fine.
This Worked for me (at the GetRandomColor):
Random random = new Random();
return Color.FromArgb((byte)random.Next(0, 255), (byte)random.Next(0, 255), (byte)random.Next(0, 255));
private Color color;
private int b;
public Color Random()
{
Random r = new Random();
b = r.Next(1, 5);
switch (b)
{
case 1:
{
color = Color.Red;
}
break;
case 2:
{
color = Color.Blue;
}
break;
case 3:
{
color = Color.Green;
}
break;
case 4:
{
color = Color.Yellow;
}
break;
}
return color;
}
I guess brushGet
gets called before MainForm_Load
could have created random
.
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