Question Problem With Code, object reference not set

bgreer5050

New member
Joined
Jul 4, 2009
Messages
4
Programming Experience
Beginner
The first time this code runs, it works fine. The second time it runs I get an error of "Object reference not set to an instance of an object" on the followng line:

lblTagNo.Text = (DataGridView1.CurrentRow.Cells(1).Value.ToString())

The entire code for the page is:
VB.NET:
Imports System.Data
Imports System.Data.OleDb
Imports System.Configuration
Imports System.Web.Configuration

Public Class frmTag


    Private Sub frmTag_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Me.DataGridView1.Visible = False
        Dim dsTag As DataSet = New DataSet
        Dim cnTag As OleDb.OleDbConnection
        cnTag = New OleDb.OleDbConnection
        cnTag.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\databases\mwst.mdb"
        Dim strQuery As String
        cnTag.Open()
        strQuery = "Select * from slitcoils WHERE ID=" & recId
        Dim daTags As OleDb.OleDbDataAdapter
        daTags = New OleDb.OleDbDataAdapter(strQuery, cnTag)


        ' removing old rows
        If dsTag.Tables.Count > 0 Then
            dsTag.Tables(0).Rows.Clear()
        End If

        daTags.Fill(dsTag, "Tags")
        Me.DataGridView1.DataSource = dsTag.Tables(0)

        'close connection
        cnTag.Close()

        lblTagNo.Text = (DataGridView1.CurrentRow.Cells(1).Value.ToString())
        lblDate.Text = (DataGridView1.CurrentRow.Cells(2).Value.ToString())
        lblGage.Text = (DataGridView1.CurrentRow.Cells(3).Value.ToString())
        lblGrade.Text = (DataGridView1.CurrentRow.Cells(4).Value.ToString())
        lblHeatNo.Text = (DataGridView1.CurrentRow.Cells(7).Value.ToString())
        lblPO.Text = (DataGridView1.CurrentRow.Cells(8).Value.ToString())
        lblDescription.Text = (DataGridView1.CurrentRow.Cells(11).Value.ToString())
        lblCustomer.Text = (DataGridView1.CurrentRow.Cells(13).Value.ToString())
        lblWorkOrder.Text = (DataGridView1.CurrentRow.Cells(14).Value.ToString())

    End Sub
End Class
 
You're going about this the wrong way. You've bound the data to your grid so you should bind it to your Labels too. That way they will all update automatically, e.g.
VB.NET:
lblTagNo.DataBindings.Add("Text", dsTag.Tables(0), "TagNo")
You do that for each Label, using the appropriate column name for each, and you'll avoid your current issue and you also won't have to worry about updating the Labels if you select a different row in the grid.
 
Back
Top