开发者

NullReferenceException error in VB Application?

开发者 https://www.devze.com 2023-02-24 02:53 出处:网络
I\'m building a voting system for calls, and have tried to build it in VB. So far this is what I have:

I'm building a voting system for calls, and have tried to build it in VB. So far this is what I have:

    Dim con As New OleDb.OleDbConnection
    Dim dbProvider As String
    Dim dbSource As String

    dbProvider = "PROVIDER=Microsoft.Jet.OLEDB.4.0;"
    dbSource = "Data Source = C:\PhonePoll.mdb"

    con.ConnectionString = dbProvider & dbSource

    con.ConnectionString = "PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source = C:\PhonePoll.mdb"

    con.Open()

    'sql = "SELECT * FROM voting"
    'da = New OleDb.OleDbDataAdapter(sql, con)
    'da.Fill(ds, "voting")

    If inc <> -1 Then

        Dim cb As New OleDb.OleDbCommandBuilder(da)
        Dim dsNewRow As DataRow

        dsNewRow = ds.Tables("voting").NewRow()
        dsNewRow.Item("voted") = RadioButton1.Checked.ToString
        dsNewRow.Item("voted") = RadioButton2.Checked.ToString
        dsNewRow.Item("voted") = RadioButton3.Checked.ToString
        dsNewRow.Item("voted") = RadioButton4.Checked.ToString

        ds.Tables("voting").Rows.Add(dsNewRow)

        da.Update(ds, "voting")

        开发者_如何学编程MsgBox("New Record added to the Database")

    End If

    MsgBox("Phone call has been logged")

    con.Close()

This code is contained within a "Record Call" button. On the form, there are four radio buttons, all with different text values which should be entered in to the "voting" table.

My problem is that when I select a radio button and click on "Record Button" it then displays this error:

NullReferenceException: Object reference not set to an instance of an object.

This error is displayed on the line

dsNewRow = ds.Tables("voting").NewRow()

I'm not sure what I've done wrong.

Cheers for the help!


I am assuming in the real code you don't have the SQL and Fill() method for the dataset commented out and that is just a typo in the code above - right? If I am wrong and that block of code is commented out, then your dataset is null and that's the issue...


Don't put all that code on one line - Split it up. Either ds is null, or ds.Tables("voting") returns something null, but you will never know because it's transitory. And you can't check it, because you didn't store it in a variable

That's why I try to never calls too long:

A b = me.foo.bar.baz.fuz.bom() <- Just asking for trouble!


ds is null, its not initialized

maybe if you unquote:

'sql = "SELECT * FROM voting"
'da = New OleDb.OleDbDataAdapter(sql, con)
'da.Fill(ds, "voting")
0

精彩评论

暂无评论...
验证码 换一张
取 消