2014-09-01 81 views
1

我有一个程序,我正在清除用户正在用来回答多项选择题的组合框。如果用户点击清除,弹出消息框并询问用户是否确定要清除表单。如果他们按是,清除所有组合框。截至目前,如果用户按下否,它仍然清除组合框。VB.NET - MessageBox是没有条件声明不起作用

代码:

Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click 

    MessageBox.Show("Are you sure you want to clear your answers?", "Attention!",    MessageBoxButtons.YesNo) 
    If Windows.Forms.DialogResult.Yes Then 
     For Each cbo As ComboBox In Controls.OfType(Of ComboBox)() 
      cbo.Items.Clear() 
     Next 
    End If 


End Sub 
+1

这将永远不会工作,因为'是= 6'。到目前为止,您的状况如下所示:“If(6 = True)Then'。你需要从'MessageBox.Show'中捕获返回值。 – 2014-09-01 17:15:09

+1

虽然使用'MessageBox.Show'与MsgBox相称! – Plutonix 2014-09-01 17:51:10

回答

3

您需要捕获的MessageBox结果:

Dim dlgR as DialogResult 

DlgR = MessageBox.Show("Are you sure you want to clear your answers?", 
      "Attention!", MessageBoxButtons.YesNo) 

' then test it: 
If dlgR = DialogResult.Yes Then 
    For Each cbo As ComboBox In Controls.OfType(Of ComboBox)() 
     cbo.Items.Clear() 
    Next 
End If 

MessageBox是它返回一个DialogResult功能。您的代码

If Windows.Forms.DialogResult.Yes Then... 

未评估用户的响应; DialogResult.Yes不是False(0),所以它永远是真的,并且无论他们回答什么,都会导致CBO被清除。

此外,该代码在Option Strict下不合法。如果Option Strict打开,VB/VS会通知您这一点并提示您更改它;这样可以避免在其他地方出现许多类似的更严重的错误。

+0

谢谢!工作完美 哇,我只是意识到,cbo.Items.Clear()清除组合框drowndownlist的内容。 有没有办法清除用户的选择,但保留内容? (内容是A,B,C和D)多项选择题 – user2308700 2014-09-01 17:16:21

+0

我想知道你为什么要删除答案列表...将Items.Clear改为'。Text =“”' – Plutonix 2014-09-01 17:19:52

0

您可以用下面的方法也:

If MsgBox("Are you sure you want to clear your answers?", MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then 
     cbo.Items.Clear() 
    Else 
     'false condition to be executed 
    End If 

注:要清除你不需要使用一个迭代循环cbo.Items.Clear()将清除组合框中

如果你想要的项目列表组合框项目除去特定项目从您可以用两种方法

  • 基础上item

    cbo.Items.Remove("Item As string")

实施例:cbo.Items.Remove("Apple")

  • 基于Index

    cbo.Items.RemoveAt(Index As Integer)

例如:cbo.Items.RemoveAt(2)

+0

我更喜欢这种方法,因为dialogresult在评估之后是“垃圾收集”,而不是保留在if语句下面的范围的内存中。看起来更干净。 – Chad 2014-09-01 21:37:41

+0

@Chad你知道'MsgBox'是一个封装的函数,最后调用'MessageBox.Show'? http://referencesource.microsoft.com/#Microsoft.VisualBasic/Interaction.vb#555 – 2014-09-02 16:55:26

+0

@Bjørn-RogerKringsjå我在之前的评论中并没有提到'MsgBox';我指的是删除'DialogResult'(另一个答案有)的'Dim'语句。在没有Dim的情况下在if语句中进行一次计算会更简洁,因为它意味着代码更少,并且不需要多次检查结果(因此不需要将结果保存在内存中)。 – Chad 2014-09-03 02:30:00