从组合框中选择一个随机的SelectedIndex

时间:2018-12-03 11:05:23

标签: vb.net winforms

我正在为一个课堂项目工作,我已经完成了所需的内容。但是,我想加倍努力,并对自己感到好奇。

我有一个带物品的组合框。

  1. 扭矩
  2. 跑步者
  3. Parkade
  4. ABM
  5. 人乳
  6. Gasbar
  7. Donair
  8. 消防厅
  9. 餐巾纸
  10. 乱扔
  11. 四十磅钱
  12. 二十六或特威克斯
  13. 抱抱

到目前为止,我有用户选择的输出。无需粘贴整个代码...

Private Sub btnResults3_Click(sender As Object, e As EventArgs) Handles btnResults3.Click
     If cboCanadianisms.SelectedIndex = 0 Then
        txtResults.Text = "A knitted cap/hat, referred to as a beanie in the United States. A beanie is a completely different type of hat in Canada. "
    ElseIf cboCanadianisms.SelectedIndex = 1 Then
        txtResults.Text = "Referred to as sneakers or tennis shoes in the United States."

,依此类推。

我的问题-有没有办法使第二个按钮显示带有所附文本的随机选择。

代码

txtResults.Text = "You have chosen " & 
cboCanadianisms.Items.Item(myRandom.Next(i)).ToString

,但这仅显示组合框中的13个项目之一,没有附加文本。

谢谢

3 个答案:

答案 0 :(得分:0)

您是否尝试过在选择/组合框中获取有界项的文本值?

Dim randomNumber As Integer = myRandom.Next(i); 
txtResults.Text = "You have chosen " & 
cboCanadianisms.Items.Item(randomNumber ).ToString & cboCanadianisms.Items.Item(randomNumber ).Text;

答案 1 :(得分:0)

(注意:我目前没有VB编译器,因此该代码中可能存在一些错误)

首先,您不应该依赖方法中的SelectedIndex,因为如果有人在列表顶部添加内容,它将完全中断。理想情况下,您应该创建一个由TitleDescription组成的类,并使用该类-但这可能还要花很多时间:)

首先,让我们修改代码以支持您想要实现的目标。我们没有创建在事件处理程序中显示描述的代码,而是创建了一个方法,该方法将选定的索引作为参数,并返回该描述:

Function getDescription(ByVal index As Integer) As String
    Select Case index
        Case 0:
            Return "A knitted..."
        Case 1:
            Return "Referred to as sn..."
        Case Else:
            Return ""
End Function

使用此功能,我们可以将整个事件处理程序替换为:

txtResults.Text = getDescription(cboCanadianisms.SelectedIndex)

感谢这一点,我们也可以在代码的随机部分中使用它:

Dim number as Integer = myRandom.Next(i)
txtResults.Text = "You have chosen " & cboCanadianisms.Items.Item(number).ToString & ": " & getDescription(number)

答案 2 :(得分:0)

有点晚了,但这是我的尝试,我将Descriptions放入了一个字符串列表(可以随意编辑以匹配您的定义),并通过Random函数使其随机化:

Private Sub btnResults2_Click(sender As Object, e As EventArgs) Handles btnResults2.Click

    Dim Descriptions() As String = {"A knitted cap/hat", "Referred to as sneakers...", "Description 3",
                                "Description 4", "Description 5", "Description 6",
                                "Description 7", "Description 8", "Description 9",
                                "Description 10", "Description 11", "Description 12", "Description 13"}

    Dim ListofDesc As List(Of String) = Descriptions.ToList
    Dim count As Integer = 0
    Dim Selected As Integer = 0

    For i As Integer = 0 To 13
        count = ListofDesc.Count
        Selected = MyRand.Next(0, count)
        cboCanadianisms.SelectedIndex = Selected
    Next

End Sub

我只是用一个小型的winforms应用程序进行了尝试,每次我们按下btnResults2按钮时,它都会为ComboBox显示一个随机生成的新选择。希望这会有所帮助!