MrLucky Posted March 5, 2006 Posted March 5, 2006 I've this function: public static Color GetRandomColor() { Random random = new Random(); return Color.FromArgb(random.Next(256), random.Next(256), random.Next(256)); } I use this function here: int[] values; string[] legends; Color[] colors; values = new int[10]; legends = new string[10]; colors = new Color[10]; int i = 0; while(reader.Read()) { values[i] = Convert.ToInt32(reader.GetValue(reader.GetOrdinal("total_played"))); legends[i] = reader.GetValue(reader.GetOrdinal("history_artist")) + " - " + reader.GetValue(reader.GetOrdinal("history_title")); colors[i] = ChartUtil.GetRandomColor(); i += 1; } So for every entry in DB, I thought there will be an other color. But, in practice, every entry has the same color :confused: How can I fix this? Quote
Leaders snarfblam Posted March 5, 2006 Leaders Posted March 5, 2006 The random class uses the time as a seed. You are probably creating the random objects so quickly that the computer clock does not advance throughout the process, meaning that you get the same seed every time. What you most likely will want to do is create one random object and re-use it so that this will never be a problem. static Random randomclr = new Random(); public static Color GetRandomColor() { return Color.FromArgb(randomclr.Next(256), randomclr.Next(256), randomclr.Next(256)); } Quote [sIGPIC]e[/sIGPIC]
Cags Posted March 5, 2006 Posted March 5, 2006 Well at first I was convinced there was something wrong elsewhere in your code, as from what you've posted I couldn't see an error, but then I gave it a quick test. If you call GetRandomColor() from a button click and then click the button repeatedly, it always returns a different colour. However when called from a loop it returns the same colour for a set amount of time. If you had more items in your loop you would have discovered that after a certain amount the colour changes. Assumably this is down to the way random generates a number. I remember back in the days of VB 6 you needed to pass a seed to avoid always getting the same value. To counter this many people passed a tickcount. Perhaps in .Net this is automatically done. Calling the method repeatedly over such a period of time however would mean the tickcount stays the same for several iterations of the call. I'm sorry, this doesn't solve your problem, but hopefully shines some light on why its happenign. Quote Anybody looking for a graduate programmer (Midlands, England)?
Cags Posted March 5, 2006 Posted March 5, 2006 Beaten to the punch, what he said ^. Quote Anybody looking for a graduate programmer (Midlands, England)?
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.