我正在尝试找到一种基于选择单选按钮来运行某些代码的方法。我在组合框中有几个单选按钮,它们将根据选择运行不同的代码。现在,作为一个相当新的VB.NET用户,我正在努力正确编码。
使用IF语句或SELECT CASE语句会更好吗?我尝试使用标志设置为布尔值来指示是否选择了button1,设置了flag = true。就我而言。我正在使用CheckedChanged事件来处理事件更改。我已经包含了一些代码,如果有人能让我开始,我将不胜感激。非常感谢。
Private Sub rdbBoxReturn_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles rdbBoxReturn.CheckedChanged
'code goes here
flagBoxReturn = True
End Sub
Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
Try
If flagBoxReturn = True Then
MessageBox.Show(CStr(flagBoxReturn))
Return
Else
DBConnection.connect()
sql = "SELECT MAX([Id]) from Request Boxes WHERE Customer = '" & cmbCustomer.Text & "' "
'MessageBox.Show(cmbCustomer.Text)
'sql = "INSERT INTO [Requests] ("")"
'Dim sql As String = "SELECT * from Boxes WHERE Customer = ? AND Status = 'i'"
Dim cmd As New OleDb.OleDbCommand
Dim id As String
Dim requestor As String = "DEMO"
Dim intake As String = "I"
Dim status As String = "O"
'cmd.Parameters.AddWithValue("@p1", cmbCustomer.Text)
cmd.CommandText = sql
cmd.Connection = oledbCnn
dr = cmd.ExecuteReader
'lvSelectRequestItems.Items.Clear()
While dr.Read()
id = CStr(CInt(dr.Item(0).ToString))
id = String.Format("{0:D6}", (Convert.ToInt32(id) + 1))
'id = CStr(CDbl(id) + 1)
End While
MessageBox.Show(CStr(id))
dr.Close()
sql = "INSERT INTO [Request Boxes] ([Request no], Customer, Dept, [Type], [Service level], [Date-time received], [Received by], [Date-time due], Quantity, [Cust requestor], Status ) " &
"VALUES ('" & id & "', '" & cmbCustomer.Text.ToUpper & "', '" & cmbDept.Text & "', '" & intake.ToString & "', '" & rbServiceLevel.ToString & "', '" & dtpDateReceived.Value & "', '" & requestor.ToString & "', '" & dtpDateDue.Value & "', '" & txtBoxQuantity.Text & "', '" & requestor.ToString & "', '" & status & "')"
cmd.CommandText = sql
cmd.ExecuteNonQuery()
cmd.Dispose()
oledbCnn.Close()
flagBoxReturn = False
MessageBox.Show("Your record number: " & id & " Was entered successfully")
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
答案 0 :(得分:2)
这样的事情怎么样......
Public Enum SaveOption As Int32
DoNothing = 0
DoSomething = 1 ' Obviously rename this to something that makes sense in your situation.
End Enum
Public Function GetSaveOption() As SaveOption
Dim result As SaveOption = SaveOption.DoNothing
If rdbBoxReturn.Checked Then
result = DoSomething
End If
' Add as many if statements her to cover all your radio buttons.
Return result
End Function
Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
Select Case GetSaveOption
Case SaveOption.DoNothing
Exit Sub
Case SaveOption.DoSomething
' Your save code here
End Select
End Sub
此方法通过将UI元素状态转换为程序状态,使您的代码更具可读性。
答案 1 :(得分:1)
如果比较次数很少,则切换语句会更好 如果你有一个单选按钮列表控件,那就更好了 switch语句可以传递索引变量(Radio的SelectedIndex属性) 按钮列表)但该控件在Web表单中可用,或者可以在win表单中使用 如果你找到一些免费的用户/自定义控件等。
所以在你的情况下,最好使用if else语句