[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 550
  • Last Modified:

Error:System.NullReferenceException - Trying to give a Label.Text Value from Dataset

I am getting the following error.

System.NullReferenceException: Object reference not set to an instance of an object.

Line 36 is Highlighted


Line 34:             NewsIDSent = cInt(Request.QueryString("ID"))
Line 35:             GetNews(NewsIDSent)
Line 36:             TitleLabel.Text = NewsDS.Tables("tblNews").Rows(0).Item("News_Title").ToString
Line 37:       End If
Line 38:       End Sub
 
Here is the Code from GetNews Subroutine

      Sub GetNews(NewsIDSent As Integer)
            SelectStatement = "Select * From tblNews Where News_ID=" & NewsIDSent
            strConnection = ConfigurationSettings.AppSettings("ConnectionString")
            MyDBConnection.ConnectionString = strConnection
            Adapter.SelectCommand = new OleDbCommand(SelectStatement, MyDBConnection)
            NewsCB = New OleDbCommandBuilder(Adapter)
            Adapter.Fill(NewsDS,"tblNews")
      End Sub

Please can someone shed some light on this subject, I am relativly new to ASP.net

Thanks in Advance

Dave

0
tclgb
Asked:
tclgb
  • 14
  • 10
  • 7
  • +1
2 Solutions
 
ihenryCommented:
The the line 36, the error could be caused of some reasons.

1st, if there's no record matched to the sql query then record will return. So the number of rows is 0 and this line
NewsDS.Tables("tblNews").Rows(0)
will be the problem.

2nd, if the associated field name is not the same with "News_Title", then this line
NewsDS.Tables("tblNews").Rows(0).Item("News_Title")
is likely to be the problem.

3rd, or there's maybe another problem in the GetNews function.
0
 
Hamed ZaghaghiProgrammerCommented:
one of the things that may make this error is that your table has no data, so you can check it with an If statement before use it, and also, change the line that contains
     Adapter.Fill(NewsDS,"tblNews")
in GetNews sub to
     Adapter.Fill(NewsDS.Tables("tblNews"))

have a good programming day;
--hamed
0
 
w3timCommented:
Hi Dave,

All that has happened is that the query has come across an empty value in the database.  You cannot convert a Null value to a string so it throws an error.

You can fix this by simply testing for a DBNull.Value first

Try changing the line;
TitleLabel.Text = NewsDS.Tables("tblNews").Rows(0).Item("News_Title").ToString

to
If Not(NewsDS.Tables("tblNews").Rows(0).Item("News_Title") Is DBNull.Value) Then TitleLabel.Text = NewsDS.Tables("tblNews").Rows(0).Item("News_Title").ToString

Hope this helps,
Tim
0
The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

 
w3timCommented:
Ach, sorry, might be wrong on that one... Think I'm getting my errors confused.  If the other suggestions don't work try mine...

Oops!
0
 
ihenryCommented:
Tim,
I think it should be just fine to call ToString() method from a DBNull object as it will return an empty string, no?
0
 
ihenryCommented:
Oops..Tim, I didn't see your correction when I posted my last comment.
0
 
w3timCommented:
Chuckle, don't worry, I'm not 100% awake yet!!  I didn't read the error properly!!

I don't think it does though.  Can't remember to be honest.  An empty string and a null value are different... You could be right though.

*sigh* - think I need to go back to bed!!
0
 
tclgbAuthor Commented:
I have looked at the table and there is 100% data there in News_Title for News_ID=1


When changing to

Adapter.Fill(NewsDS.Tables("tblNews")) as Suggested by Hamed

I recieve the following error.

System.ArgumentNullException: Value can not be null. Parameter name: dataTable

Does this mean that my NewsDataSet is Not Being Populated as It Cannot find any records which match the query.

I have posted complete code below

Option Explicit On
Option Strict On

'-----------------------------------------------------------------------------
'
'   Module Name: DeleteNewsItems.aspx.vb
'
'   Description: This module provides the code behind for the
'                DeleteNewsItem.aspx page
'
'*****************************************************************************
Imports System
Imports System.IO
Imports System.Web.UI
Imports System.Data
Imports System.Data.OleDb

Namespace TBO.News
  Public Class DeleteItems
    Inherits System.Web.UI.Page

        Dim TitleLabel As Label
      Dim Message As Label
      Dim Submit As Button
      Dim ConnectString, SelectStatement As String
      Dim Connect As OleDbConnection = New OleDBConnection
      Dim Adapter As OleDBDataAdapter = New OleDbDataAdapter
      Dim NewsCB as OleDBCommandBuilder
      Dim NewsDS As DataSet = New Dataset
      Dim NewsIDSent As Integer
      
      Sub Page_Load(Sender As Object, E As EventArgs)
      If Not IsPostBack Then
         NewsIDSent = cint(Request.QueryString("ID"))
         GetNews(NewsIDSent)
         TitleLabel.Text = _
              NewsDS.Tables("tblNews").Rows(0).Item("News_Title").ToString
      End If
      End Sub
      
      Sub Submit_Click(Sender As Object, E As EventArgs)
            
            NewsIDSent = cInt(Request.QueryString("ID"))
            
            GetNews(NewsIDSent)
            
            NewsDS.Tables("tblNews").Rows(0).Delete
            
            Adapter.Update(NewsDS, "tblNews")
            
            If NewsDS.HasErrors Then
                  Message.Text = "There was an error deleting the News Item. " & NewsDS.Tables("tblNews").Rows(0).RowError
            Else
                  Message.Text = "The News Item has been removed"
                  Submit.Enabled=False
            End If
      End Sub
      
      Sub GetNews(NewsIDSent As Integer)
      SelectStatement = "Select * From tblNews Where News_ID=" & NewsIDSent
      ConnectString = ConfigurationSettings.AppSettings("ConnectionString")
      Connect.ConnectionString = ConnectString
      Adapter.SelectCommand = _
         new OleDbCommand(SelectStatement, Connect)
      NewsCB = New OleDbCommandBuilder(Adapter)
      Adapter.Fill(NewsDS.Tables("tblNews"))

      End Sub
      
  End Class  'Delete News
End Namespace




0
 
w3timCommented:
As a suggestion, try changing;

Adapter.Fill(NewDS.Tables("tblNews"))

to

Adapter.Fill(NewDS)

If you get the original error again then try adding
Throw New Exception(NewDS.Tables("tblNews").Rows.Count)

That should show you if you are returning any rows.

If you're not then double check your query and make sure you're requesting a valid ID.  If you're not then try it with a valid ID and change

TitleLabel.Text = _
            NewsDS.Tables("tblNews").Rows(0).Item("News_Title").ToString

to

If NewsDS.Tables("tblNews").Rows.Count > 0 Then
      TitleLabel.Text = _
            NewsDS.Tables("tblNews").Rows(0).Item("News_Title").ToString
End If

Hope this helps,

Tim
0
 
ihenryCommented:
Dave, with just  a

Adapter.Fill(NewsDS)

should be more than enough. By the way, are you sure there's a table named "tblNews" in your database?

Now, let start some debugging with this code

If Tables("tblNews").Rows.Count < 0 Then
 TitleLabel.Text = NewsDS.Tables(0).Rows(0)("News_Title").ToString
End If

Any row return?
0
 
ihenryCommented:
Oops...Tim again I didn't see your post..I think I need some coffee.. :o)
0
 
w3timCommented:
You and me both, chuckle, today is not going well!!!
0
 
tclgbAuthor Commented:
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:


Line 39:    '   End If
Line 40:         
Line 41:         If NewsDS.Tables("tblNews").Rows.Count < 0 Then
Line 42:  TitleLabel.Text = NewsDS.Tables(0).Rows(0)("News_Title").ToString
Line 43: End If
 

Line 41 Causes this Error

It seems that NewsDS is Not an Object ?????

0
 
w3timCommented:
Before;
Adapter.Fill

add

NewsDS = New DataSet

Let us know if it works!
0
 
ihenryCommented:
I see, I'm still not sure what happen though. How about using this one?

 If NewsDS.Tables(0).Rows.Count < 0 Then
 TitleLabel.Text = NewsDS.Tables(0).Rows(0)("News_Title").ToString
End If

0
 
ihenryCommented:
>> NewsDS = New DataSet
Tim, I think he got it
0
 
ihenryCommented:
Oopss..I did it again..

I mean this one..sorry for the typo..

If NewsDS.Tables(0).Rows.Count > 0 Then
 TitleLabel.Text = NewsDS.Tables(0).Rows(0)("News_Title").ToString
End If

0
 
tclgbAuthor Commented:
I have NewsDS = New DataSet at Top where all variables are declared.

I have added it again before Adapter.Fill but still makes no difference

This does not make any sense
0
 
ihenryCommented:
mm..I think I can see now what's the problem..

in the page_load replace the code with this

        NewsIDSent = cint(Request.QueryString("ID"))
        GetNews(NewsIDSent)
        TitleLabel.Text = _
            NewsDS.Tables("tblNews").Rows(0).Item("News_Title").ToString

without postback condition.
0
 
tclgbAuthor Commented:
I have also tried the ihenry suggestion and stil the same error.
0
 
ihenryCommented:
You mean you have tried the past post?
0
 
tclgbAuthor Commented:
Sorry must have been posting at the same time.

I have now tried the past post and still the same error.

Code is now as follows

        Dim TitleLabel As Label
      Dim Message As Label
      Dim Submit As Button
      Dim ConnectString, SelectStatement As String
      Dim Connect As OleDbConnection = New OleDBConnection
      Dim Adapter As OleDBDataAdapter = New OleDbDataAdapter
      Dim NewsCB as OleDBCommandBuilder
      Dim NewsDS As DataSet = New Dataset
      Dim NewsIDSent As Integer
      
      Sub Page_Load(Sender As Object, E As EventArgs)
'         If NewsDS.Tables("tblNews").Rows.Count > 0 Then
 '     TitleLabel.Text = _
  '          NewsDS.Tables("tblNews").Rows(0).Item("News_Title").ToString
   '   End If
               NewsIDSent = cint(Request.QueryString("ID"))
        GetNews(NewsIDSent)
        TitleLabel.Text = NewsDS.Tables("tblNews").Rows(0).Item("News_Title").ToString
      End Sub
      
      Sub Submit_Click(Sender As Object, E As EventArgs)
            
            NewsIDSent = cInt(Request.QueryString("ID"))
            
            GetNews(NewsIDSent)
            
            NewsDS.Tables("tblNews").Rows(0).Delete
            
            Adapter.Update(NewsDS, "tblNews")
            
            If NewsDS.HasErrors Then
                  Message.Text = "There was an error deleting the News Item. " & NewsDS.Tables("tblNews").Rows(0).RowError
            Else
                  Message.Text = "The News Item has been removed"
                  Submit.Enabled=False
            End If
      End Sub
      
      Sub GetNews(NewsIDSent As Integer)
      SelectStatement = "Select * From tblNews Where News_ID=" & NewsIDSent
      ConnectString = ConfigurationSettings.AppSettings("ConnectionString")
      Connect.ConnectionString = ConnectString
      Adapter.SelectCommand = _
         new OleDbCommand(SelectStatement, Connect)
      NewsCB = New OleDbCommandBuilder(Adapter)
      Adapter.Fill(NewsDS)
End Sub
0
 
Hamed ZaghaghiProgrammerCommented:
don't use table name for dataset, and call it like this:
NewDS.Tables(0).Rows(0).......

and in GetNews sub
change :
Adapter.Fill(NewsDS.Tables("tblNews"))

with

Adapter.Fill(NewsDS)


 
0
 
ihenryCommented:
Dave, try this code

Sub Page_Load(Sender As Object, E As EventArgs)
      If Not Request.QueryString("ID") Is Nothing Then
            Try
                  NewsIDSent = Integer.Parse(Request.QueryString("ID"))
            Catch
                  ' incorrect string integer format or overflow
                  Return
            End Try

            GetNews( NewsIDSent )
            TitleLabel.Text = "Empty"
            If NewsDS.Tables(0).Rows.Count > 0 Then
                  TitleLabel.Text = NewsDS.Tables(0).Rows(0)("News_Title").ToString
            End If
      End If
End Sub

..decaf house blend...anyone?
0
 
w3timCommented:
Ach, do you have caffinated?
0
 
tclgbAuthor Commented:
Henry,
Tried your code snippet

Problem on Line 40 which is TitleLabel.Text = "Empty"

Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:


Line 40:
Line 41:           GetNews( NewsIDSent )
Line 42:           TitleLabel.Text = "Empty"
Line 43:           If NewsDS.Tables(0).Rows.Count > 0 Then
Line 44:                TitleLabel.Text = NewsDS.Tables(0).Rows(0)("News_Title").ToString
 
0
 
ihenryCommented:
Haha..dave..do you really have TitleLabel control in your page? I see only the variable declaration nothing else.

I think if you put the control in your page the declaration should look like this

Protected WithEvents TitleLabel As System.Web.UI.WebControls.Label
0
 
ihenryCommented:
Tim, caffinated coffee is not good for your health.
0
 
Hamed ZaghaghiProgrammerCommented:
try this:


Option Explicit On
Option Strict On

'-----------------------------------------------------------------------------
'
'   Module Name: DeleteNewsItems.aspx.vb
'
'   Description: This module provides the code behind for the
'                DeleteNewsItem.aspx page
'
'*****************************************************************************
Imports System
Imports System.IO
Imports System.Web.UI
Imports System.Data
Imports System.Data.OleDb

Namespace TBO.News
  Public Class DeleteItems
    Inherits System.Web.UI.Page

       Dim TitleLabel As Label
     Dim Message As Label
     Dim Submit As Button
     Dim ConnectString, SelectStatement As String
     Dim Connect As OleDbConnection = New OleDBConnection
     Dim Adapter As OleDBDataAdapter = New OleDbDataAdapter
     Dim NewsCB as OleDBCommandBuilder
     Dim NewsDS As DataSet = New Dataset
     Dim NewsIDSent As Integer
     
     Sub Page_Load(Sender As Object, E As EventArgs)
     If Not IsPostBack Then
        NewsIDSent = cint(Request.QueryString("ID"))
        GetNews(NewsIDSent)
        TitleLabel.Text = _
            NewsDS.Tables(0).Rows(0).Item("News_Title").ToString
     End If
     End Sub
     
     Sub Submit_Click(Sender As Object, E As EventArgs)
         
          NewsIDSent = cInt(Request.QueryString("ID"))
         
          GetNews(NewsIDSent)
         
          NewsDS.Tables(0).Rows(0).Delete
         
          Adapter.Update(NewsDS.Tables(0))
         
          If NewsDS.HasErrors Then
               Message.Text = "There was an error deleting the News Item. " & NewsDS.Tables("tblNews").Rows(0).RowError
          Else
               Message.Text = "The News Item has been removed"
               Submit.Enabled=False
          End If
     End Sub
     
     Sub GetNews(NewsIDSent As Integer)
     SelectStatement = "Select * From tblNews Where News_ID=" & NewsIDSent
     ConnectString = ConfigurationSettings.AppSettings("ConnectionString")
     Connect.ConnectionString = ConnectString
     Adapter.SelectCommand = _
        new OleDbCommand(SelectStatement, Connect)
     NewsCB = New OleDbCommandBuilder(Adapter)
     Adapter.Fill(NewsDS)

     End Sub
     
  End Class  'Delete News
End Namespace
0
 
Hamed ZaghaghiProgrammerCommented:
and check that
NewsIDSent after this line
>>  NewsIDSent = cint(Request.QueryString("ID"))
has a valid value;
0
 
w3timCommented:
Henry, I gave up smoking I think giving up coffee you tip me over the edge!
0
 
tclgbAuthor Commented:
Thanks for all your help guys

I had
Dim TitleLabel As Label      
Changed to
Protected TitleLabel As Label

The actual label is on DeleteNewsItem.aspx and this code was from the Code Behind If that makes sense.

Apologies for Newbieness
0
 
w3timCommented:
Chuckle, it's always the simple things like that that drive you up the wall!!

Glad you got it sorted :)!
0
 
ihenryCommented:
Hahaha..

Dave,
we glad your problem solved.

Tim,
life is beautiful..

Have a nice day everyone!
0
 
w3timCommented:
It is?!  Maybe it's the miserable weather that's making that hard to see ;)!

Have a nice day all :)!
0

Featured Post

Learn to develop an Android App

Want to increase your earning potential in 2018? Pad your resume with app building experience. Learn how with this hands-on course.

  • 14
  • 10
  • 7
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now