Random Generator Names in a Drop Down Box
I am trying to write a program that will randomly generate a list of names that are in a drop down box. Example: In one drop down box, I have 6 names, and when I press the Generate button, I want it to randomly pick one of those names in the box. I am not familiar with c# completely. I appreciate everyone's help in this for me.
Jan MontanoPosted Feb 3, 2009, 8:20 PM
DerrickPosted Feb 3, 2009, 1:13 PM
Thank you very much! It worked!
Now here's another question, if I have the same names that appear in the drop down boxes, how can I set it up to not appear twice in a drop down box?
Jan MontanoPosted Feb 3, 2009, 11:33 AM
//I double clicked on my form for it to create a form1_load event
private void Form1_Load(object sender, EventArgs e)
{
listBox1.Items.Add("Jan");
listBox1.Items.Add("Aimee");
listBox1.Items.Add("Cjo");
}
//I double-clicked on the button for it to create a button1_click event
private void button1_Click(object sender, EventArgs e)
{
Random randomizer = new Random();
// to be used in reading the items in the list box. in this scenario, listBox1.Items.Count is equal to 3. so the randomizer.next generates numbers from 0 up to 3-1, or simply put: 0 to 2.
int randomIndex = randomizer.Next(0, listBox1.Items.Count);
string randomName = listBox1.Items[randomIndex].ToString();
textBox1.Text = randomName;
}