好的,所以我有一个名为quote_guidelines的表单,我想使用一个过程来更新我的数据库,并在quote_guidelines表单中输入值。价值观是装饰,食品/饮料和娱乐的描述和成本。已为每个选项卡分配了其中一个附加服务。我想创建一个用这些新值更新数据库的过程。 问题是查询必须包含不同的表和不同的文本框名称。我试图通过在变量中保存表和文本框的名称来解决这个问题,然后将其传递给过程。
表变量在sql语句中工作正常但是,文本框名称不行。 我试过这个:
quote_guidelines.Controls(description_textbox).Text
但这不起作用。
这是我的问题:
query = "UPDATE " & additional & " SET description='" & quote_guidelines.Controls("" & description_textbox & "").Text & "', cost= " & quote_guidelines.Controls("" & cost_textbox & "").Text & " WHERE " & additional & "ID='" & y & "'"
当我运行程序时,我收到以下错误“EHCC_BookingSystem.exe中发生了'System.NullReferenceException'类型未处理的异常
附加信息:对象引用未设置为对象的实例。“
我刚刚意识到这可能是我犯过的其他一些愚蠢的错误,所以这就是整个程序:
Sub UpdateAdditionals(textbox3 As System.Object, textbox4 As System.Object, textbox5 As System.Object, textbox6 As System.Object, textbox7 As System.Object, textbox8 As System.Object, ByRef additional As String, ByRef description_textbox As String, ByRef cost_textbox As String)
mysqlconn = New MySqlConnection
mysqlconn.ConnectionString = "Server=localhost;userid=root;password=root;database=comp4"
Dim reader As MySqlDataReader
MsgBox(additional & description_textbox & cost_textbox)
Try
mysqlconn.Open()
Dim query As String
query = "UPDATE " & additional & " SET description='" & quote_guidelines.Controls.Find(description_textbox, True).FirstOfDefault().Text & "', cost= " & quote_guidelines.Controls.Find(cost_textbox, True).FirstOfDefault().Text & " WHERE " & additional & "ID='" & y & "'"
MsgBox(query)
command = New MySqlCommand(query, mysqlconn)
reader = command.ExecuteReader()
mysqlconn.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
mysqlconn.Dispose()
End Try
End Sub
答案 0 :(得分:0)
试试这个 - 在Controls
中替换Controls.Find
(注意`True参数来搜索控件子项):
query = "UPDATE " & additional & " SET description='" & TryCast(quote_guidelines.Controls.Find(description_textbox, True)(0), TextBox).Text & "', cost= " & TryCast(quote_guidelines.Controls.Find(cost_textbox, True)(0).Text & " WHERE " & additional & "ID='" & y & "'"
另请注意,您可以.FirstOfDefault()
获取第一个控件(不要忘记施放):
Controls.Find("nameofcontrol", True).FirstOfDefault()