how to show two seperate random items from 2 listb

2019-08-28 16:00发布

问题:

I have 2 listbox, one for 'names' and one for 'what they did' I have a textbox assigned to each of these listbox and an add button for each so the user can enter whatever 'name' or 'what they did' they want into the 2 listbox. I have a create button which will show the result of this in a message box and thats easy, but I want it to show a random combination each time.

So in the 'name' listbox I could have entered the names Jerry, Dean, Mary and in the 'what they did' I could have entered Sat, Slept, Cried. On the press of the create button I want a random item from both lists so the result could be 'Dean Cried' then the next time I press create it could be 'Jerry Slept'

I have been able to, with some help get a random item on each press of the create button from the name box but I am having trouble getting my code to make it happen for both.

    private void btnaddname_Click(object sender, EventArgs e)
    {
        stringname = textBoxname.Text;
        textBoxname.Clear();
        listboxname.Items.Add(stringname);    
    }


    private void btnaddwhat_Click(object sender, EventArgs e)
    {
        stringwhat = textBoxwhat.Text;
        textBoxwhat.Clear();
        listBoxwhat.Items.Add(stringwhat);
    }


    private void buttoncreate_Click(object sender, EventArgs e)
    {
        Random random = new Random();
        int randomNumber = random.Next(1, listboxname.Items.Count);
        listboxname.Select();
        listboxname.SelectedItem = listboxname.Items[randomNumber];


        Random randomwhat = new Random();
        int randomnumwhat = randomwhat.Next(1, listBoxwhat.Items.Count);
        listBoxwhat.Select();
        listBoxwhat.SelectedItem = listBoxwhat.Items[randomnumwhat];

        MessageBox.Show(listboxname.SelectedItem.ToString() + (" ") + (listBoxwhat.SelectedItem.ToString()));

    }

回答1:

Try to create just one Random variable and use it for both list...

Random random = new Random();
int randomNumber = random.Next(1, listboxname.Items.Count);
listboxname.Select();
listboxname.SelectedItem = listboxname.Items[randomNumber];


int randomnumwhat = random.Next(1, listBoxwhat.Items.Count);
listBoxwhat.Select();
listBoxwhat.SelectedItem = listBoxwhat.Items[randomnumwhat];

MessageBox.Show(listboxname.SelectedItem.ToString() + (" ") +(listBoxwhat.SelectedItem.ToString()));