SQL和GridView

时间:2012-03-21 15:59:05

标签: asp.net .net vb.net

我目前正在为葡萄酒的网络服务做一个项目。我有wineName和wineType的酒桌。我还在webservice编码中实现了搜索功能,以及一个单独的webform来调用搜索功能的功能

我有以下用于在搜索服务中执行搜索的代码:

<WebMethod()> _
Public Function Search(ByVal searchName As String) As System.Data.DataSet
    Dim connectionString As String = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
    Dim con As New SqlConnection(connectionString)

    Dim selectSql As String = "SELECT * From Wine WHERE WineType='" & searchName + "'"

    Dim selectAdapter As New Data.SqlClient.SqlDataAdapter(selectSql, con)
    Dim ds As New Data.DataSet
    con.Open()
    selectAdapter.Fill(ds, "Wine")
    con.Close()

    Return ds

End Function

至于webform,它只是一个简单的页面,文本框标记为searchName,按钮和gridView1绑定到ObjectDataSource。

这是我对webform的编码:

Partial Class Search
    Inherits System.Web.UI.Page

    Dim searching As searchwine.Service = New searchwine.Service

    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        If searchName.Text = "" Then
            lblDisplayError.Text = "Can't search empty field!"

        Else

            Dim ds As DataSet = searching.Search(searchName.Text)
            GridView1.DataSource = ds.Tables(0)
            GridView1.DataBind()
            GridView1.Visible = True
            lblDisplayError.Visible = False

        End If

    End Sub

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        lblDisplayError.Text = ""
        GridView1.Visible = False
    End Sub

End Class

一切似乎都很好,但是当我想要搜索时出现以下错误:

  

System.NullReferenceException:未将对象引用设置为对象的实例。在Service.Search(String searchName)

有人可以帮帮我吗?

2 个答案:

答案 0 :(得分:1)

我已经查看过你的代码几次了,我看不出是什么导致了NullReferenceException。我最好的猜测是它在你的web.config文件中找不到连接字符串名称“ConnectionString”,但即使这样也不太合适。

我可以建议对搜索代码进行一些改进。希望你至少能得到一个更好的错误信息:

<WebMethod()> _
Public Function Search(ByVal searchName As String) As System.Data.DataSet
    Dim ds As New Data.DataSet()
    Dim connectionString As String = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString

    Using con As New SqlConnection(connectionString), _
          cmd As New SqlCommand("SELECT * From Wine WHERE WineType= @SearchName", con)

        'I had to guess at the exact length and type of the field here
        cmd.Parameters.Add("@SearchName", SqlDbType.VarChar, 50).Value = searchName 

        Dim selectAdapter As New Data.SqlClient.SqlDataAdapter(cmd, con)
        selectAdapter.Fill(ds, "Wine")
    End Using

    Return ds
End Function

但最后我希望您需要逐步完成该方法,并确切地看到上面的哪一行引发异常。

答案 1 :(得分:-1)

您似乎错过了New

Dim ds As DataSet = searching.Search(searchName.Text)

应该......

Dim ds As **New** DataSet = searching.Search(searchName.Text)