I am trying to show info at the bottom of my data grid I get error saying object reference not set to an instance of an object Here is my code Imports System.data
Imports System.data.OleDb
Imports System.Configuration
Partial Class supplier
Inherits System.Web.UI.Page
Dim ConnString As String = ConfigurationManager.AppSettings("ConnString")
Dim dbPath As String = ConfigurationManager.AppSettings("PathDB")

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
getsuppliers()
dgsuppliers.DataSource = Session("Suppliers")

End If
End Sub


Private Sub getsuppliers()


Dim mySQL As String = "select * from Suppliers "
Dim dbConn As New OleDbConnection(ConnString & Server.MapPath(dbPath))
Dim dbCommand As New OleDbCommand(mySQL, dbConn)
Dim dbAdapter As New OleDbDataAdapter(dbCommand)
Dim dsSuppliers As New DataSet


Try
dbConn.Open()
dbAdapter.Fill(dsSuppliers, "Suppliers")
Catch ex As Exception
lblResults.Text = "Error occurred when retrieving data from Table: " & ex.Message
Finally
dbConn.Close()
End Try
dgsuppliers.DataSource = dsSuppliers
dgsuppliers.DataBind()
End Sub
Private Sub dgsuppliers_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles dgsuppliers.PageIndexChanging
End Sub

Protected Sub dgsuppliers_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles dgsuppliers.SelectedIndexChanged

Dim mysql As String = "Select * from Suppliers where SupplierID=" & dgsuppliers.SelectedValue & ""
Dim dbConn As New OleDbConnection(ConnString & Server.MapPath(dbPath))
Dim dbCommand As New OleDbCommand(mysql, dbConn)
Dim dbAdapter As New OleDbDataAdapter(dbCommand)
Dim dsSuppliers As New DataSet
Dim supplierRow As DataRow

supplierRow = dsSuppliers.Tables("Suppliers").Rows(0)
supplierRow("CompanyName") = lblName.Text
supplierRow("ContactName") = lblContact.Text
supplierRow("ContactTitle") = lblTitle.Text
supplierRow("Address") = lblAddress.Text
supplierRow("City") = lblCity.Text
supplierRow("Region") = lblRegion.Text
supplierRow("PostalCode") = lblPostal.Text
supplierRow("Country") = lblCountry.Text
supplierRow("Phone") = lblPhone.Text
supplierRow("Fax") = lblFax.Text
supplierRow("Homepage") = lblHomepage.Text
dsSuppliers.Tables.Add("Suppliers").Rows.Add(supplierRow)

dgsuppliers.DataSource = dsSuppliers.Tables

End Sub
End Class

Dani AI

Generated

Short diagnosis: the NullReference happens because you create a fresh DataSet in SelectedIndexChanged and then try to read a table/row that does not exist. Also, Page_Load reads Session("Suppliers") but your getsuppliers routine never saves its DataSet into Session, and the GridView DataKeyNames in the markup looks inconsistent with the actual column name — any of those will make SelectedValue/DataKeys be null.

Fix approach (pick one that fits your design):

  • Persist the result set: after filling the DataSet in getsuppliers(), store it (Session("Suppliers") = ds) and bind the GridView to that table. In SelectedIndexChanged pull the DataSet back from Session, check the table exists and has rows, then locate the row for the selected SupplierID and populate the labels.
  • Re-query the database in SelectedIndexChanged for the selected SupplierID (preferred if the dataset is large). Use a parameterized SELECT WHERE SupplierID = ? so you only fetch one row and then map fields to labels.
  • Use the GridView DataKeys properly: set DataKeyNames to the exact column name (for example SupplierID), then read SelectedDataKey.Value to get the ID and proceed as above.

Notes on replies already here:

  • is right that a DataRow must come from the DataTable. You cannot instantiate a DataRow with New DataRow; you must create it via the table (or fill schema first, as suggested).
  • ’s advice about creating a new DataRow directly is incorrect — creating rows requires an existing DataTable schema.

Quick safety checklist and troubleshooting tips:

  • After Fill, set Session("Suppliers") = ds if you plan to reuse it.
  • Always check for Nothing and Tables.Contains("Suppliers") and Rows.Count > 0 before accessing rows.
  • Make DataKeyNames exactly match the column name used in the result set.
  • Avoid concatenating SQL; use parameters.
  • Use Using blocks or Dispose/Close in Finally for connections.

Example guard (VB) — use this pattern before accessing a row:

If Session("Suppliers") Is Nothing Then Exit Sub
Dim ds As DataSet = CType(Session("Suppliers"), DataSet)
If Not ds.Tables.Contains("Suppliers") OrElse ds.Tables("Suppliers").Rows.Count = 0 Then Exit Sub
Dim found() As DataRow = ds.Tables("Suppliers").Select("SupplierID = " & dgsuppliers.SelectedValue)
If found.Length > 0 Then lblName.Text = found(0)("CompanyName").ToString()

Recommended Answers

All 5 Replies

i can see two possible problems

to add a new row to a dataset user datarows
supplierRow = dsSuppliers.Tables("Suppliers").NewRow

and when binding to tables you need to declare the table
dgsuppliers.DataSource = dsSuppliers.Tables
("Suppliers")

I am trying to show info at the bottom of my data grid I get error saying object reference not set to an instance of an object Here is my code Imports System.data
Imports System.data.OleDb
Imports System.Configuration
Partial Class supplier
Inherits System.Web.UI.Page
Dim ConnString As String = ConfigurationManager.AppSettings("ConnString")
Dim dbPath As String = ConfigurationManager.AppSettings("PathDB")

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
getsuppliers()
dgsuppliers.DataSource = Session("Suppliers")

End If
End Sub


Private Sub getsuppliers()


Dim mySQL As String = "select * from Suppliers "
Dim dbConn As New OleDbConnection(ConnString & Server.MapPath(dbPath))
Dim dbCommand As New OleDbCommand(mySQL, dbConn)
Dim dbAdapter As New OleDbDataAdapter(dbCommand)
Dim dsSuppliers As New DataSet


Try
dbConn.Open()
dbAdapter.Fill(dsSuppliers, "Suppliers")
Catch ex As Exception
lblResults.Text = "Error occurred when retrieving data from Table: " & ex.Message
Finally
dbConn.Close()
End Try
dgsuppliers.DataSource = dsSuppliers
dgsuppliers.DataBind()
End Sub
Private Sub dgsuppliers_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles dgsuppliers.PageIndexChanging
End Sub

Protected Sub dgsuppliers_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles dgsuppliers.SelectedIndexChanged

Dim mysql As String = "Select * from Suppliers where SupplierID=" & dgsuppliers.SelectedValue & ""
Dim dbConn As New OleDbConnection(ConnString & Server.MapPath(dbPath))
Dim dbCommand As New OleDbCommand(mysql, dbConn)
Dim dbAdapter As New OleDbDataAdapter(dbCommand)
Dim dsSuppliers As New DataSet
Dim supplierRow As DataRow

supplierRow = dsSuppliers.Tables("Suppliers").Rows(0)
supplierRow("CompanyName") = lblName.Text
supplierRow("ContactName") = lblContact.Text
supplierRow("ContactTitle") = lblTitle.Text
supplierRow("Address") = lblAddress.Text
supplierRow("City") = lblCity.Text
supplierRow("Region") = lblRegion.Text
supplierRow("PostalCode") = lblPostal.Text
supplierRow("Country") = lblCountry.Text
supplierRow("Phone") = lblPhone.Text
supplierRow("Fax") = lblFax.Text
supplierRow("Homepage") = lblHomepage.Text
dsSuppliers.Tables.Add("Suppliers").Rows.Add(supplierRow)

dgsuppliers.DataSource = dsSuppliers.Tables

End Sub
End Class

Ehy dear,
Please follow the following steps:
1. add this line in getsuppliers() function in try block
dbconn.dospose()

2. In dgsuppliers_SelectedIndexChanged function you have declared datarow. Your line of code is as follows:

Dim supplierRow As DataRow

change it as follows:

Dim supplierRow As new DataRow

or

Dim supplierRow as DataRow = New DataRow()
Your problem is solved now.

I have checked it. You have not declared the instance of datarow. Thats why it was giving an error.

I tried but I still have a problem. I am trying to show info at the bottom of my grid when I click on a command field in my table. I am stuck on how to finish. The design code for the grid is here

%@ Page Language="VB" AutoEventWireup="false" CodeFile="" Inherits="supplier" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
&nbsp; &nbsp;


<asp:GridView ID="dgsuppliers" runat="server" AllowPaging="True" AutoGenerateColumns="False" CellPadding="4" DataKeyNames ="SupplierId"
foreColor="#333333" GridLines= "None">

<Columns>
<asp:BoundField DataField="SupplierID" HeaderText="Supplir ID " />
<asp:BoundField DataField="CompanyName" HeaderText="Supplier Name" />
<asp:CommandField SelectText="More Details" ShowSelectButton="True"/>
</Columns>
<RowStyle BackColor="#0E3AEB" />
<EditRowStyle BackColor="#7C6F57" />
<SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" Forecolor="#333333" />
<PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />
<HeaderStyle BackColor="#01CE55" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor ="White" />


</asp:GridView>
<br />
<asp:Label ID="lblName" runat="server" Width="344px"></asp:Label><br />
<asp:Label ID="lblContact" runat="server" Width="344px"></asp:Label><br />
<asp:Label ID="lblAddress" runat="server" Width="344px"></asp:Label><br />
<asp:Label ID="lblCity" runat="server" Width="344px"></asp:Label> <br />
<asp:Label ID="lblPhone" runat="server" Width="344px"></asp:Label><br />
<asp:Label ID="lblFax" runat="server" Width="344px"></asp:Label><br />
<asp:Label ID="lblTitle" runat="server" Width="344px"></asp:Label><br />
<asp:Label ID="lblRegion" runat="server" Width="344px"></asp:Label> <br />
<asp:Label ID ="lblPostal" runat="server" Width="344px"></asp:Label><br />
<asp:Label ID="lblCountry" runat="server" Width="344px"></asp:Label><br />

<asp:Label ID="lblHomepage" runat="server" Width="344px"></asp:Label><br />

<asp:Label ID="lblResults" runat="server" Text="Label"></asp:Label>

<div>

</div>
</form>
</body>
</html>

hey i have checked it out. Okay do one thing. I am still not getting the kind of problem you have. Better mail me following things:

1. Code
2. Error message copy + paste
3. Error message print screen
4. Purpose of code.

Mail above details on

Thank you.
Regards

do this mydataset.fillschema and then create new row as ds.table("tablename").newrow.

i think this will solve ur problem.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.