VB.NET - MessageBox YesNo 条件语句不起作用 [英] VB.NET - MessageBox YesNo Conditional Statement not working
问题描述
我有一个程序,用于清除用户用来回答多项选择题的组合框.如果用户单击清除,则会弹出一个消息框并询问用户是否确定要清除表单.如果他们按是,它会清除所有组合框.截至目前,如果用户按否",它仍会清除组合框.
I have a program where I am clearing out comboboxes that the user is using to answer multiple choice questions. If the user clicks Clear, a messagebox pops up and asks the user if they are sure they want to clear out the form. If they press yes, it clears out all comboboxes. As of right now, if the user presses no, it still clears out the comboboxes.
代码:
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
推荐答案
您需要捕获 MessageBox 结果:
You need to capture the MessageBox result:
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
的函数.你的代码
MessageBox
is a function which returns a DialogResult
. Your code
If Windows.Forms.DialogResult.Yes Then...
不评估用户的响应;DialogResult.Yes
不是 False (0),因此它将始终为 True 并导致 CBO 无论他们回答什么都会被清除.
isnt evaluating the user's response; DialogResult.Yes
is not False (0), so it will always be True and cause the CBOs to be cleared no matter what they answer.
此外,该代码在 Option Strict
下是不合法的.如果 Option Strict
开启,VB/VS 会通知你并提示你改变它;这将避免在其他地方出现许多类似且更严重的错误.
Also, that code is not legal under Option Strict
. VB/VS would inform you of this and prompt you to change it if Option Strict
is on; this will avoid many similar - and more serious - errors elsewhere.
这篇关于VB.NET - MessageBox YesNo 条件语句不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!