?
Solved

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

Posted on 2005-04-01
35
Medium Priority
?
549 Views
Last Modified: 2009-07-29
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
Comment
Question by:tclgb
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 14
  • 10
  • 7
  • +1
35 Comments
 
LVL 20

Expert Comment

by:ihenry
ID: 13679456
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
 
LVL 9

Expert Comment

by:zaghaghi
ID: 13679468
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
 
LVL 4

Expert Comment

by:w3tim
ID: 13679476
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
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
LVL 4

Expert Comment

by:w3tim
ID: 13679483
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
 
LVL 20

Expert Comment

by:ihenry
ID: 13679514
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
 
LVL 20

Expert Comment

by:ihenry
ID: 13679524
Oops..Tim, I didn't see your correction when I posted my last comment.
0
 
LVL 4

Expert Comment

by:w3tim
ID: 13679560
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
 

Author Comment

by:tclgb
ID: 13679581
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
 
LVL 4

Expert Comment

by:w3tim
ID: 13679649
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
 
LVL 20

Expert Comment

by:ihenry
ID: 13679687
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
 
LVL 20

Expert Comment

by:ihenry
ID: 13679701
Oops...Tim again I didn't see your post..I think I need some coffee.. :o)
0
 
LVL 4

Expert Comment

by:w3tim
ID: 13679712
You and me both, chuckle, today is not going well!!!
0
 

Author Comment

by:tclgb
ID: 13679721
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
 
LVL 4

Assisted Solution

by:w3tim
w3tim earned 200 total points
ID: 13679731
Before;
Adapter.Fill

add

NewsDS = New DataSet

Let us know if it works!
0
 
LVL 20

Expert Comment

by:ihenry
ID: 13679733
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
 
LVL 20

Expert Comment

by:ihenry
ID: 13679737
>> NewsDS = New DataSet
Tim, I think he got it
0
 
LVL 20

Expert Comment

by:ihenry
ID: 13679755
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
 

Author Comment

by:tclgb
ID: 13679769
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
 
LVL 20

Expert Comment

by:ihenry
ID: 13679774
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
 

Author Comment

by:tclgb
ID: 13679790
I have also tried the ihenry suggestion and stil the same error.
0
 
LVL 20

Expert Comment

by:ihenry
ID: 13679792
You mean you have tried the past post?
0
 

Author Comment

by:tclgb
ID: 13679817
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
 
LVL 9

Expert Comment

by:zaghaghi
ID: 13679844
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
 
LVL 20

Expert Comment

by:ihenry
ID: 13679853
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
 
LVL 4

Expert Comment

by:w3tim
ID: 13679865
Ach, do you have caffinated?
0
 

Author Comment

by:tclgb
ID: 13679876
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
 
LVL 20

Accepted Solution

by:
ihenry earned 1800 total points
ID: 13679893
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
 
LVL 20

Expert Comment

by:ihenry
ID: 13679898
Tim, caffinated coffee is not good for your health.
0
 
LVL 9

Expert Comment

by:zaghaghi
ID: 13679902
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
 
LVL 9

Expert Comment

by:zaghaghi
ID: 13679907
and check that
NewsIDSent after this line
>>  NewsIDSent = cint(Request.QueryString("ID"))
has a valid value;
0
 
LVL 4

Expert Comment

by:w3tim
ID: 13679910
Henry, I gave up smoking I think giving up coffee you tip me over the edge!
0
 

Author Comment

by:tclgb
ID: 13679918
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
 
LVL 4

Expert Comment

by:w3tim
ID: 13679936
Chuckle, it's always the simple things like that that drive you up the wall!!

Glad you got it sorted :)!
0
 
LVL 20

Expert Comment

by:ihenry
ID: 13679938
Hahaha..

Dave,
we glad your problem solved.

Tim,
life is beautiful..

Have a nice day everyone!
0
 
LVL 4

Expert Comment

by:w3tim
ID: 13679963
It is?!  Maybe it's the miserable weather that's making that hard to see ;)!

Have a nice day all :)!
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

I have developed many web applications with asp & asp.net and to add and use a dropdownlist was always a very simple task, but with the new asp.net, setting the value is a bit tricky and its not similar to the old traditional method. So in this a…
In .NET 2.0, Microsoft introduced the Web Site.  This was the default way to create a web Project in Visual Studio 2005.  In Visual Studio 2008, the Web Application has been restored as the default web Project in Visual Studio/.NET 3.x The Web Si…
Add bar graphs to Access queries using Unicode block characters. Graphs appear on every record in the color you want. Give life to numbers. Hopes this gives you ideas on visualizing your data in new ways ~ Create a calculated field in a query: …
Do you want to know how to make a graph with Microsoft Access? First, create a query with the data for the chart. Then make a blank form and add a chart control. This video also shows how to change what data is displayed on the graph as well as form…
Suggested Courses

765 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question