Click here to Skip to main content
15,900,816 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi
I am trying to create a stored procedure for retrieving data from tables. Code is

VB
Public Sub SelectData()
        dim table,OPtable as string
        SqlQuery = "Select * from " & table & ""
        Sqlcommand = New MySqlCommand(SqlQuery, Conn)
        'Reader = Sqlcommand.ExecuteReader
        count = Sqlcommand.ExecuteScalar
        Dim Da As New MySqlDataAdapter
        Dim Ds As New DataSet
        Da.SelectCommand = Sqlcommand
        Da.Fill(Ds, OPtable)
        MessageBox.Show(Ds.Tables(OPtable).Rows(0)("Name")) -- All OK till here
End Sub

now when i call above procedure with following code

VB
Private Sub BtnFirst_Click_1(sender As Object, e As EventArgs) Handles BtnFirst.Click
        table = "Ledgers"
        OPtable = "LEDG"

        Try
            SelectData()
            TxtName.Text = Ds.Tables("LEDG").Rows(2)("Name") // error occurs here

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


error is object reference not set to instance of an object

What I have tried:

when I copy code in stored procedure to button click event everything works fine.

I am trying to move records (first, last, next, previous). I was thinking of collecting records from a table into Dataset(Ds) and then move it as required. Is there any simpler way to do this?
Posted
Updated 12-Dec-17 14:47pm
v3
Comments
Bryian Tan 11-Dec-17 23:04pm    
Maybe there only 1 row in the table? have you try Rows(0) also instead of 2?

1 solution

table and OPtable variables are declared inside SelectData method, meaning they are local variables and are inaccessible outside of the method they are declared in.

You should pass them as method parameters instead: Public Sub SelectData(ByVal table as string, ByVal OPtable as string), and then call the method providing it with their values: SelectData("Ledgers", "LEDG").
 
Share this answer
 
Comments
Member 13550326 12-Dec-17 0:33am    
tried your solution but same error occurs
phil.o 12-Dec-17 0:53am    
Then it means that either DS is null, or Tables("LEDG") is null, or there is no third row in LEDG table. Why third row (Rows(2)) anyway? Couldn't you just retrieve only the row you're interested in?
Member 13550326 12-Dec-17 5:59am    
both DS as tables("LEDG") are not null because when i run the same code in button click event , output is as expected.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900