对于下面显示的代码,如果发生错误,我将如何使用try / catch块来处理错误?
TOTKILO.Text = KILO.Text * TOUCH.Text * 0.01
TextBox10.Text = TextBox9.Text * TextBox8.Text * 0.01
K = Math.Round(Val(TOTKILO.Text) - Val(TextBox10.Text), 5)
TextBox11.Text = TextBox7.Text + K
cmd.CommandType = Data.CommandType.Text
con.ConnectionString = "Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Documents and Settings\Administrator\My Documents\Visual Studio 2005\Projects\SHOPPROJECT\SHOPPROJECT\shop.mdf;Integrated Security=True;User Instance=True"
con.Open()
If RadioButton1.Checked Then
GOLD = 1
ElseIf RadioButton2.Checked Then
SILVER = 1
End If
If RadioButton3.Checked Then
KGOLD = 1
ElseIf RadioButton4.Checked Then
KSILVER = 1
End If
cmd.CommandText = " INSERT INTO SALES VALUES('" & ComboBox1.Text & " ' , " & SILVER & " ," & GOLD & ",'" & ComboBox2.Text & "'," & KILO.Text & ", " & TOUCH.Text & " ," & TOTKILO.Text & "," & TextBox3.Text & "," & TextBox8.Text & "," & KGOLD & "," & KSILVER & "," & TextBox9.Text & " ," & TextBox10.Text & "," & TextBox11.Text & "," & TextBox12.Text & " , " & TextBox13.Text & " ) "
cmd.CommandType = " UPDATE BALANCE SET OBBALANCE = " & TextBox11.Text & " WHERE CUSTOMERNAME = '" & ComboBox1.Text & "' "
cmd.Connection = con
cmd.ExecuteNonQuery()
con.Close()
END SUB
我使用VB.Net控件和LINQ to SQL来执行所有更新和插入,所以当出现错误时我想显示“正确输入数据”,一旦我发现异常,我该怎么做?
答案 0 :(得分:1)
我在下面添加了一个简单的Try ... Catch,但我认为你会发现你有很多问题:
以下是修改后的代码:
Try
TOTKILO.Text = KILO.Text * TOUCH.Text * 0.01
TextBox10.Text = TextBox9.Text * TextBox8.Text * 0.01
K = Math.Round(Val(TOTKILO.Text) - Val(TextBox10.Text), 5)
TextBox11.Text = TextBox7.Text + K
cmd.CommandType = Data.CommandType.Text
con.ConnectionString = "Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Documents and Settings\Administrator\My Documents\Visual Studio 2005\Projects\SHOPPROJECT\SHOPPROJECT\shop.mdf;Integrated Security=True;User Instance=True"
con.Open()
If RadioButton1.Checked Then
GOLD = 1
ElseIf RadioButton2.Checked Then
SILVER = 1
End If
If RadioButton3.Checked Then
KGOLD = 1
ElseIf RadioButton4.Checked Then
KSILVER = 1
End If
cmd.CommandText = " INSERT INTO SALES VALUES('" & ComboBox1.Text & " ' , " & SILVER & " ," & GOLD & ",'" & ComboBox2.Text & "'," & KILO.Text & ", " & TOUCH.Text & " ," & TOTKILO.Text & "," & TextBox3.Text & "," & TextBox8.Text & "," & KGOLD & "," & KSILVER & "," & TextBox9.Text & " ," & TextBox10.Text & "," & TextBox11.Text & "," & TextBox12.Text & " , " & TextBox13.Text & " ) "
cmd.CommandType = " UPDATE BALANCE SET OBBALANCE = " & TextBox11.Text & " WHERE CUSTOMERNAME = '" & ComboBox1.Text & "' "
cmd.Connection = con
cmd.ExecuteNonQuery()
Catch (ex as Exception)
MsgBox.Show("Enter Data Correctly: " & ex.toString)
Finally
con.Close()
End Try