0

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.

2
Contributors
1
Reply
2
Views
7 Years
Discussion Span
Last Post by __avd
0

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

Edited by mike_2000_17: Fixed formatting

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.