如果选择了所有四个组合框中的相同项目

时间:2018-03-07 09:31:58

标签: arrays vb.net combobox

newb练习更多vb.net代码。 我目前有四个相同的组合框名为box1,box2,box3,box4。 在每个组合框中我都有一个单词列表 -

我通过'properties' - >'items' - >'collections'标签添加了这些单词。

现在,我想要显示一条消息 - “你有4只猫!”如果用户为所有四个组合框选择单词'cat'。

我该如何编写此代码?我猜我引入了一个像'onlycats'这样的私有函数,看看是否为所有4个盒子选择了'cat'......但我不确定如何根据用户从组合框中选择的内容进行编码。< / p>

2 个答案:

答案 0 :(得分:0)

因此,您希望计算ComboBox的选择,并在用户按下按钮后将结果显示为MsgBox。你可以这样做:

    Dim Selection(4) As String
    Selection(0) = box1.Text
    Selection(1) = box2.Text
    Selection(2) = box3.Text
    Selection(3) = box4.Text
    MsgBox("You selected " & Selection.Where(Function(value) value = "dog").Count & " dogs!")

首先,我将所有内容添加到数组中,然后搜索特定值并对其进行计数。你可以这样算:

Selection.Where(Function(value) value = "value").Count

输出为数字。如果&#34; dog&#34;在所有4个框中选中,然后输出只是4,你可以在它周围写一个文本。希望它能带你走上正轨。

============

如果您只想在选择4只猫时触发某些事情,那么计数功能也可以帮助您。只需制作一个If函数

If Selection.Where(Function(value) value = "cat").Count = 4 Then
   MsgBox("you have 4 cats!")
End If

答案 1 :(得分:0)

未经测试的代码,但是像这样:

sub CheckSame
  if box2.SelectedValue = box1.SelectedValue
      andalso box3.SelectedValue = box1.SelectedValue
      andalso box4.SelectedValue = box1.selectedValue then
    message.text = "You have 4 " & plural(box1.SelectedValue) & "!"
  else
    message.text = "You don't have 4 of the same animal"
  end if
end sub

function plural(s as String) as String
  select case s
    case "fish"
      return "fish"
    case else
      return s & "s"
  end select
end function