早上好,
我正在使用ASP.NET 3.5 webforms应用程序并编写了以下代码:
Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubmit.Click
Dim connectionString As String = WebConfigurationManager.ConnectionStrings("Diel_inventoryConnectionString").ConnectionString
Dim con As New SqlConnection(connectionString)
Dim adapter1 As New SqlDataAdapter
adapter1.SelectCommand = New SqlCommand
adapter1.SelectCommand.CommandType = CommandType.StoredProcedure
adapter1.SelectCommand.CommandText = "PartSproc"
Dim parmNSN As New SqlParameter("@NSN", SqlDbType.NVarChar)
Dim parmName As New SqlParameter("@PartName", SqlDbType.NVarChar)
txtNSN.Text = adapter1.SelectCommand.Parameters("@NSN").Value
txtSearch.Text = adapter1.SelectCommand.Parameters("@PartName").Value
Dim dt As New DataTable()
adapter1.Fill(dt)
MySearch.DataSource = dt
MySearch.DataBind()
End Sub
当我运行该页面时,我收到错误此SQLParameter Collection未包含带有@NSN的SQLParameter。我尝试在@NSN和@PartName周围使用撇号,但这也不起作用并且呈现表达式预期错误。
我如何纠正上述代码,以便正确引用@NSN和@PartName参数?
编辑:下面的新代码
Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubmit.Click
Dim connectionString As String = WebConfigurationManager.ConnectionStrings("Diel_inventoryConnectionString").ConnectionString
Dim con As New SqlConnection(connectionString)
Dim cmd As New SqlCommand("PartSproc", con)
cmd.CommandType = CommandType.StoredProcedure
Dim adapter1 As New SqlDataAdapter
Dim parmNSN As New SqlParameter("@NSN", SqlDbType.NVarChar)
Dim parmName As New SqlParameter("@PartName", SqlDbType.NVarChar)
adapter1.SelectCommand.Parameters.Add(parmNSN)
adapter1.SelectCommand.Parameters.Add(parmName)
adapter1.SelectCommand.Parameters("@NSN").Value = txtNSN.Text
adapter1.SelectCommand.Parameters("@PartName").Value = txtSearch.Text
Using con
Dim dt As New DataTable()
adapter1.SelectCommand = cmd
adapter1.Fill(dt)
MySearch.DataSource = dt
MySearch.DataBind()
End Using
End Sub
我现在收到错误对象引用未设置为引用add参数parmNSN的对象的实例。我真的需要那些添加paraameter语句,因为我已经将它们设置为等于下面的文本框了吗?
谢谢, SID
答案 0 :(得分:1)
我认为你不小心改变了参数值的分配 - 试试这个:
adapter1.SelectCommand.Parameters("@NSN").Value = txtNSN.Text
adapter1.SelectCommand.Parameters("@PartName").Value = txtSearch.Text
答案 1 :(得分:0)
您是否阅读了错误消息?您创建的Sql参数永远不会添加到命令的Sqlparameter集合中;)这就是错误消息也会让您满意的。
你创建参数,但它们“悬而未决”,可以说。
答案 2 :(得分:0)
添加到Andrew& TomTom说,您需要将参数添加到SelectCommand
的参数集合中。
像
这样的东西adapter1.SelectCommand.Parameters.Add(parmNSN);
adapter1.SelectCommand.Parameters.Add(parmName);
在拨打ExecuteReader()
或ExecuteScalar