Hi,

I'm trying to use datareader to retrieve a column and place the value in a textbox.

When I try to assign the value to the text field, I get an error message "An unhandled exception of type 'System.NullReferenceException' occurred

Additional information: Object reference not set to an instance of an object."

This is the code I wrote:
[Public Class Form1
Inherits System.Windows.Forms.Form
Dim DBConnection As New SqlConnection()
Dim DBCommand As SqlCommand
Dim DBReader As SqlDataReader
Dim SQLString As String

Private Sub form1_load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

DBConnection = New SqlConnection()
DBConnection.ConnectionString = ("Server=AGU;Database=Northwind;Integrated security=true")
DBConnection.Open()
SQLString = "SELECT productname FROM products where productname like 'Ch%' ORDER BY productid"
DBCommand = New SqlCommand(SQLString, DBConnection)
DBReader = DBCommand.ExecuteReader(CommandBehavior.SingleRow)
While DBReader.Read()
TextBox1.Text = DBReader.Item("productname").ToString()
End While
DBReader.Close()
DBConnection.Close()
End Sub
]

I can display the value on the screen with msgbox, but I can't assign it to the textbox. I tried assigning it first to a variable and then to the textbox, but I got the same error.

Can anyone help me please?

Thanks in advance.

Please verify your code. Use bb code-tags to post source code.

Public Class Form1
    Inherits System.Windows.Forms.Form
    Dim DBConnection As SqlConnection()
    Dim DBCommand As  SqlCommand
    Dim DBReader As SqlDataReader
    Dim SQLString As String

Private Sub form1_load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
   DBConnection = New SqlConnection()
   DBCommand = new SqlCommand()
   DBConnection.ConnectionString="Server=AGU;Database=Northwind;Integrated security=true"
DBConnection.Open()
   SQLString = "SELECT productname FROM products where productname like 'Ch%' ORDER BY productid"
   DBCommand = New SqlCommand(SQLString, DBConnection)
   DBReader = DBCommand.ExecuteReader(CommandBehavior.SingleRow)
  IF DBReader.Read()
        TextBox1.Text = DBReader.Item("productname").ToString()
   End While
   DBReader.Close()
   DBConnection.Close()
End Sub
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.