Object reference not set to an instance of an object.

vanisri

Member
Joined
Mar 12, 2007
Messages
6
Programming Experience
Beginner
Hi

I'm trying to retreive data into textbox using Sql database.
the error points at "tb2.Text = ds.Tables[0].Rows[r].ItemArray[0].ToString()" and "if rowindex == (ds.Tables[0].Rows.Count - 1) then" while I'm trying to view the next record(data row) in the data table and the error is "Object reference not set to an instance of an object".
I have created an Userdefined Method as "RecordDisplay(int r)" where 'r' is the row index.
Where I could be wrong?

vanisri

VB.NET:
Sub RecordDisplay(ByVal r As Integer)
 tb2.Text = ds.Tables(0).Rows(r).ItemArray(0).ToString()
 tb1.Text = ds.Tables(0).Rows(r).ItemArray(1).ToString()
 tb3.Text =ds.Tables(0).Rows(r).ItemArray(2).ToString()
End Sub
 
Dim rowindex As Integer = 0
 
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
 Dim con As New SqlConnection("Server=(local);DataBase='Northwind';uid='sa'")
 Dim adap As New SqlDataAdapter("select * from Phonedetails", con)
 Dim ds As New DataSet
 adap.Fill(ds, "phonedetails")
 dg1.DataSource = ds.Tables("phonedetails")
 RecordDisplay(rowindex)
End Sub
 
'to view the next record
 
private sub btn_Click(ByVal sender As Object, ByVal e As EventArgs) Handles bt1.Click
 If rowindex = ds.Tables(0).Rows.Count - 1 then
    bt1.enabled=true
 Else
    rowindex += 1
    RecordDisplay(rowindex)
 End If
End Sub
 
check variable declaration

It gives that message where you didn't declare a variable with a new key word. so check you variable declarations and try to insert new keyword to those variable declaration.

Alos, I see in ur code that ds is declared within form1_load sub so I think u can't access that in ur btn_click sub. Declare ur dataset,ds as global variable in ur class.
 
hi
I have declared Dataset as global Variable.Then the error Points at the same place but the error is "Cannot find Table 0" and the exception is "Index Out Of Range exception" occured. Then I have given the table name in place of "0" then I got the same error as "Object reference not set to an instance of an object".So where is the mistake?
thanks srija
vanisri
 
Your dataset doesnt contain any tables. Like any collection with zero elements, you cannot successfully access the first element. Ensure your dataset contains at least one DataTable
 
PS; youre on 2005, we dont do data access like that any more. See the DW2 link in my signature.. section "Fetching data into your application"
 
hi cjard
thank u every much . i have tried using ur link. i could retrieve the data.
I want to move to a particular record for ex i want to retrieve 100th row of a data table .then how i have to proceed.
bye
vanisri
 
Well, noone ever wants to retrieve the 100th row of a database table.. they might want all people whose surname is smith , or all invoices over 100 unpaid..

Read the DW2 link, section on search forms..
 
Back
Top