简体   繁体   English

如何将两个单独的随机项目从2个列表框中显示到一个消息框中?

[英]how to show two seperate random items from 2 listbox into a messagebox?

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. 我有2个列表框,一个用于“名称”,一个用于“它们所做的事情”,我为每个这些列表框分配了一个文本框,并为每个列表框添加了一个添加按钮,以便用户可以输入任何“名称”或“他们做了什么”想要进入2列表框。 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' 在按下创建按钮时,我希望从两个列表中都选择一个随机项目,因此结果可能是“ Dean Cried”,然后在下次按下创建时可能是“ 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()));

    }

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()));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM