变量' SDA'在被赋值之前使用。在运行时可能会导致空引用异常

时间:2017-10-31 11:24:24

标签: mysql vb.net

我实际上遇到了这方面的问题,你能帮帮我吗? 我还是初学者,我不知道如何解决这个问题......

Private Sub textSearch_TextChanged(sender As Object, e As EventArgs) Handles textSearch.TextChanged

    MysqlConn = New MySqlConnection
    MysqlConn.ConnectionString =
    "server=localhost;userid=root;password=root;database=student_info"

    Dim SDA As MySqlDataAdapter
    Dim dbDataSet As New DataTable
    Dim DV As New DataView(dbDataSet)
    Dim bsource As New BindingSource
    Dim Query As String
    Dim COMMAND As MySqlCommand
    Dim ds As New DataSet
    Try
        Query = "select * from std_info where firstname like ' % " & textSearch.Text & " % '"
        SDA.Fill(ds)
        COMMAND = New MySqlCommand(Query, MysqlConn)
        bsource.DataSource = dbDataSet
        DataGridView1.DataSource = bsource
        SDA.Update(dbDataSet)
        MysqlConn.Close()
    Catch ex As Exception
        MessageBox.Show(ex.Message)
    Finally
        MysqlConn.Dispose()
    End Try
End Sub

2 个答案:

答案 0 :(得分:1)

错误发生是因为你声明了它

Dim SDA As MySqlDataAdapter

但在调用

之前未实例化(即将其设置为对象的实例)
SDA.Fill(ds)

我不知道你的代码究竟是做什么的,因为我从来没有使用MySQL等,但至少尝试类似

Query = "select * from std_info where firstname like ' % " & textSearch.Text & " % '"
COMMAND = New MySqlCommand(Query, MysqlConn)
SDA = new MySqlDataAdapter(COMMAND)
SDA.Fill(ds)

ds是一个空的新DataSet的事实让我有点担心,但这可能只是我对MySQL类的无知。

答案 1 :(得分:0)

我已经运行了程序,唯一的事情就是我仍然看不到表中的数据并将其显示到datagridview,而且当我尝试搜索时没有显示结果...帮助? (我只是一个初学者,不要生我的气。请

Private Sub textSearch_TextChanged(sender as Object,e As EventArgs)处理textSearch.TextChanged

    MysqlConn = New MySqlConnection
    MysqlConn.ConnectionString =
    "server=localhost;userid=root;password=root;database=student_info"

    Dim Query As String
    Dim COMMAND As MySqlCommand
    Dim SDA As New MySqlDataAdapter
    Dim dbDataSet As New DataTable
    Dim DV As New DataView(dbDataSet)
    Dim bsource As New BindingSource



    Try

        Query = "select * from std_info where firstname like ' % " & textSearch.Text & " % '"
        COMMAND = New MySqlCommand(Query, MysqlConn)
        SDA = New MySqlDataAdapter(COMMAND)
        SDA.Fill(dbDataSet)
        bsource.DataSource = dbDataSet
        DataGridView1.DataSource = bsource
        SDA.Update(dbDataSet)

        MysqlConn.Close()

    Catch ex As Exception
        MessageBox.Show(ex.Message)
    Finally
        MysqlConn.Dispose()
    End Try
End Sub