Solved

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

Posted on 2011-09-10
8
585 Views
Last Modified: 2012-05-12
i keep getitng the error "System.NullReferenceException: Object reference not set to an instance of an object."

Shared Function pstcount(ByVal forumname As String) As Results
        Dim con As New SqlConnection(local)
        Dim cmd As New SqlCommand
        cmd.Connection = con
        cmd.Parameters.AddWithValue("@forumname", forumname)
        Try
            con.Open()
            cmd.CommandText = "Select Count(*) From forum where Forum =@forumname"
            Dim Res As Results
            Res.Result1 = cmd.ExecuteScalar()
            cmd.CommandText = "Select Count(*) From forum where Forum =@forumname and numrep = 0  "
            Res.Result2 = cmd.ExecuteScalar()
            cmd.CommandText = "Select TOP 1  title +'|'+ LastPoster +'|'+ CONVERT(VARCHAR(256), lasttime, 120) +'|'+ CAST(ID AS VARCHAR(256)) +'|'+ CAST(numrep AS VARCHAR(256)) from forum where Forum =@forumname order by lasttime DESC"
            Res.Result3 = cmd.ExecuteScalar()

            Return (Res)
        Catch ex As Exception
            Throw ex
        Finally
            con.Close()
        End Try
    End Function

Open in new window



using :    lastrep.Text = res.Result3.Split("|")(3)

i dont understand where the error is coming from
0
Comment
Question by:runnerjp2005
  • 5
  • 3
8 Comments
 
LVL 74

Expert Comment

by:käµfm³d 👽
ID: 36516711
The problem is lines 10, 12, and 14: you haven't initialized your Res object. Try changing line 9 to:

Dim Res As New Results

Open in new window

0
 
LVL 74

Expert Comment

by:käµfm³d 👽
ID: 36516717
By the statement, "The problem is lines 10, 12, and 14," I mean that you are trying to use the properties of a class against a Null object. The lines mentioned are particularly in error, but those are the lines where your exception would be raised. Line 9 is the actual error.
0
 
LVL 74

Expert Comment

by:käµfm³d 👽
ID: 36516718
*sheesh*  I'm off my game today. Correction:

The lines mentioned are particularly in error...
This should read, "The lines mentioned are not particularly in error..."
0
 

Author Comment

by:runnerjp2005
ID: 36516742
i tried that and still get the error....

i will post full script on pages as this might be somthing somewhere else in script..
so code behinf
Imports System.Data.SqlClient
Imports System.Web.Configuration
Imports System.Web
Imports System.Data
Imports forum
Imports trackuser

Partial Class Default2
    Inherits System.Web.UI.Page
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        Dim s As String
        Dim testpage As String = s & " Forum"
        Dim forum As String = s & " Forum"
        Dim yes As Integer = onforum.noposts(forum)
        Dim usr As String
        Dim users As List(Of String) = onforum.usersonpage(forum)
        Dim UsersS As String = String.Join(",", users.ToArray)


        s = Request.QueryString("fn")
        theforum.Text = s
        ForumName.Text = s
        HyperLink3.NavigateUrl = "main.aspx"
        trackusers(testpage)

        If yes = 1 Then
            usr = " User"
        Else
            usr = " Users"
        End If

        nousers.Text = yes.ToString & usr
        Usersnames.Text = (UsersS)
        HyperLink2.PostBackUrl = "~/forums/newthread.aspx?fn=" & s
   
    End Sub



    Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs) Handles GridView1.RowDataBound

        If e.Row.RowType = DataControlRowType.DataRow Then

            Dim lastpostername As String
            Dim thepostid As Integer
            Dim lastrep As Label = CType(e.Row.FindControl("lastrep"), Label)
            Dim Hyperlink1 As ImageButton = CType(e.Row.FindControl("Hyperlink1"), ImageButton)
            Dim replies As Label = CType(e.Row.FindControl("replies"), Label)
            Dim key As Image = CType(e.Row.FindControl("key"), Image)
            Dim lastpage As ImageButton = CType(e.Row.FindControl("lastpage"), ImageButton)
            Dim s As String = e.Row.DataItem("Title")

            Dim Res As Results = pstcount(s)



            Dim myname As String = Membership.GetUser.UserName
            Dim LastDate As Date = lastpostmade(myname, "News", e.Row.DataItem("Title"))
            Dim Username As String = Membership.GetUser.UserName.ToString

            '** Design Table*'
            designtable(e)

            '**Set colours**'
            colour(e, Res, key, lastpostername, lastrep, LastDate, Username)

            '**IF it is Important**'
            importantposts(e)

            '**Set admin stuff on page**'
            adminonpage(e, Hyperlink1)


            replies.Text = Res.Result2




        End If
    End Sub

    Private Sub lastpagelink(ByVal res As Results, ByVal lastpage As ImageButton, ByVal thepostid As Integer)

        '**set the post id to either the reply or main**'
        If res.Result3.Split("|")(4) = "0" Then
            thepostid = res.Result3.Split("|")(3)
        Else
            thepostid = res.Result3.Split("|")(4)
        End If
        lastpage.PostBackUrl = "room.aspx?thread=" & thepostid & "&Page=last"

    End Sub

    Private Sub adminonpage(ByVal e As GridViewRowEventArgs, ByVal Hyperlink1 As ImageButton)
        If (User.IsInRole("Admin") = False) Then
            e.Row.Cells(6).Visible = False
        Else
            e.Row.Cells(6).Width = New Unit(75, UnitType.Pixel)
            e.Row.Cells(6).ForeColor = Drawing.Color.Red
        End If

        '**opens up the external link for admin**'
        '    Hyperlink1.Attributes.Add("onclick", "return openedit(" + e.Row.DataItem("ID").ToString + ");")
    End Sub

    Private Sub importantposts(ByVal e As GridViewRowEventArgs)

        '**If a row is important set the colour and the mouseover**'
        If e.Row.DataItem("important") = True Then
            e.Row.Attributes.Add("onmouseover", "this.originalstyle=this.style.backgroundColor;this.style.backgroundColor='lightslategray';")
            e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=this.originalstyle;")
            e.Row.BackColor = System.Drawing.ColorTranslator.FromHtml("#004466")
            e.Row.ForeColor = Drawing.Color.White
        End If
    End Sub


    Private Sub designtable(ByVal e As GridViewRowEventArgs)

        '** set row width**'
        e.Row.Cells(0).Width = New Unit(50, UnitType.Pixel)
        e.Row.Cells(1).Width = New Unit(450, UnitType.Pixel)
        e.Row.Cells(2).Width = New Unit(75, UnitType.Pixel)
        e.Row.Cells(3).Width = New Unit(100, UnitType.Pixel)
        e.Row.Cells(4).Width = New Unit(45, UnitType.Pixel)
        e.Row.Cells(5).Width = New Unit(150, UnitType.Pixel)

        '** If it is set important do the below**'
        If e.Row.RowIndex <> -1 And e.Row.DataItem("important") = False Then
            e.Row.Cells(0).BackColor = Drawing.Color.White
            e.Row.Cells(2).BackColor = Drawing.Color.White
            e.Row.Cells(4).BackColor = Drawing.Color.White
            e.Row.Attributes.Add("onmouseover", "this.originalstyle=this.style.backgroundColor;this.style.backgroundColor='#FFFFFF';this.style.color='black'")
            e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=this.originalstyle;")
        End If
    End Sub

    Function Getlastactivedate(ByVal Username As String) As String
        Dim conn As New SqlConnection(ConfigurationManager.ConnectionStrings("ApplicationServices").ConnectionString)
        Dim comm As New SqlCommand("SELECT aspnet_Users.LastActivityDate FROM aspnet_Users WHERE Username = '" & Username & "'", conn)
        conn.Open()
        Dim name As String = comm.ExecuteScalar
        conn.Close()
        Return name
    End Function

    Private Sub colour(ByVal e As GridViewRowEventArgs, ByVal res As Results, ByVal key As Image, ByVal lastpostername As String, ByVal lastrep As Label, ByVal lastdate As Date, ByVal username As String)


        '**set the colour of the lastposter to red if it is runnerjp**'
        lastrep.Text = res.Result3.Split("|")(1)
        ' If res.Result3.Split("|")(1) = "runnerjp" Then
        'lastpostername = "<font color='red'><b>" & res.Result3.Split("|")(1) & "</b></font>"
        '   Else
        ' lastpostername = "<b>" & res.Result3.Split("|")(1) & "</b>"
        '  End If

        '**set the colour of the auther to red if it is runnerjp**'
        '  lastrep.Text = "By <b>" & lastpostername & "</b> <br /> " & timeago.GetDifferenceDate(res.Result3.Split("|")(2), DateAndTime.Now)
        '  If e.Row.DataItem("Auther") = "runnerjp" Then
        'e.Row.Cells(2).ForeColor = Drawing.Color.Red
        '  End If

        '**set the colour of the folder icon if more then 150 views or 15 posts**'
        '  If e.Row.DataItem("forumlock") = False Then

        'Result2 is *No of replys*  and Result1 is *No of Views*'
        '   If res.Result2 > 15 Or res.Result1 > 150 Then
        'If Getlastactivedate(username) < lastdate Then

        '   key.ImageUrl = "~/images/thread_hot_new.gif"
        '  Else
        ' key.ImageUrl = "~/images/thread_hot.gif"
        '  End If
        '  Else
        'If Getlastactivedate(username) < lastdate Then
        'key.ImageUrl = "~/images/thread_new.gif"
        ' Else
        ' '    key.ImageUrl = "~/images/thread.gif"
        ' End If
        '  End If
        '  Else
        'key.ImageUrl = "~/images/thread_lock.gif"
        '  End If

    End Sub

  
End Class

Open in new window



and forum class
Imports Microsoft.VisualBasic
Imports System.Data.SqlClient
Imports System.Web.Configuration

Public Class forum
    Private Shared local As String = WebConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString



    Shared Function addpost(ByVal forum As String, ByVal title As String, ByVal post As String, ByVal update1 As String) As String

        Using con As New SqlConnection(local)
            Dim cmd As New SqlCommand(Nothing, con)
            Dim usernme As String = Membership.GetUser.UserName
            cmd.CommandText = "INSERT into forum (numrep,Forum,lasttime,Posttime,Auther,LastPoster,Title,Post,update1) VALUES ('0',@forum,'" & DateTime.Now.ToString("o").Substring(0, 23) & "','" & DateTime.Now.ToString("o").Substring(0, 23) & "','" & usernme & "','" & usernme & "',@title,@post,@update1)"

            cmd.Parameters.AddWithValue("@forum", forum)
            cmd.Parameters.AddWithValue("@title", title)
            cmd.Parameters.AddWithValue("@post", post)
            cmd.Parameters.AddWithValue("@update1", update1)

            con.Open()
            cmd.ExecuteNonQuery()
            con.Close()
        End Using
    End Function

    Shared Function checktitle(ByVal title As String) As Integer
        Dim con As New SqlConnection(local)
        Dim cmd As New SqlCommand
        cmd.Connection = con
        Try
            con.Open()
            Dim titlecount As Integer
            cmd.Parameters.AddWithValue("@title", title)
            cmd.CommandText = "select count(*) from forum where Title=@title"
            titlecount = cmd.ExecuteScalar()
            Return titlecount
        Catch ex As Exception
            Throw ex
        Finally
            con.Close()
        End Try
    End Function

    Shared Function replypost(ByVal numrep As String, ByVal forum As String, ByVal title As String, ByVal post As String, ByVal update1 As String) As String
        Using con As New SqlConnection(local)
            Dim cmd As New SqlCommand(Nothing, con)
            Dim cmd2 As New SqlCommand(Nothing, con)
            Dim usernme As String = Membership.GetUser.UserName
            cmd.CommandText = "INSERT into forum (numrep,Forum,lasttime,Posttime,Auther,LastPoster,Title,Post,update1) VALUES (@numrep,@forum,'" & DateTime.Now.ToString("o").Substring(0, 23) & "','" & DateTime.Now.ToString("o").Substring(0, 23) & "','" & usernme & "','" & usernme & "',@title,@post,@update1)"
            cmd2.CommandText = "Update forum SET lasttime ='" & DateTime.Now.ToString("o").Substring(0, 23) & "' Where ID =" & numrep & ""

            cmd.Parameters.AddWithValue("@numrep", numrep)
            cmd.Parameters.AddWithValue("@forum", forum)
            cmd.Parameters.AddWithValue("@title", title)
            cmd.Parameters.AddWithValue("@post", post)
            cmd.Parameters.AddWithValue("@update1", update1)
            MsgBox(cmd2.CommandText)

            con.Open()
            cmd.ExecuteNonQuery()
            cmd2.ExecuteNonQuery()
            con.Close()

        End Using
    End Function


    Shared Function views(ByVal ID As Integer) As String
        Using con As New SqlConnection(local)
            Dim cmd As New SqlCommand(Nothing, con)
            Dim usernme As String = Membership.GetUser.UserName
            cmd.CommandText = "UPDATE forum Set noviews = noviews + 1 WHERE ID=@ID"


            cmd.Parameters.AddWithValue("@ID", ID)


            con.Open()
            cmd.ExecuteNonQuery()
            con.Close()
        End Using
    End Function

    Public Structure Results
        Dim Result1 As Integer
        Dim Result2 As Integer
        Dim Result3 As String


    End Structure

    Shared Function pstcount(ByVal forumname As String) As Results
        Dim con As New SqlConnection(local)
        Dim cmd As New SqlCommand
        cmd.Connection = con
        cmd.Parameters.AddWithValue("@forumname", forumname)
        Try
            con.Open()
            cmd.CommandText = "Select Count(*) From forum where Forum =@forumname"


            Dim Reslt As New Results
            Reslt.Result1 = cmd.ExecuteScalar()
            cmd.CommandText = "Select Count(*) From forum where Forum =@forumname and numrep = 0  "
            Reslt.Result2 = cmd.ExecuteScalar()
            cmd.CommandText = "Select TOP 1  title +'|'+ LastPoster +'|'+ CONVERT(VARCHAR(256), lasttime, 120) +'|'+ CAST(ID AS VARCHAR(256)) +'|'+ CAST(numrep AS VARCHAR(256)) from forum where Forum =@forumname order by lasttime DESC"
            Reslt.Result3 = cmd.ExecuteScalar()

            Return (Reslt)
        Catch ex As Exception
            Throw ex
        Finally
            con.Close()
        End Try
    End Function
    Shared Function Newposts(ByVal name As String, ByVal forumname As String)
        Dim con As New SqlConnection(local)
        Dim cmd As New SqlCommand
        cmd.Connection = con
        Try
            con.Open()
            Dim theres As Date
            cmd.CommandText = "Select TOP 1  CONVERT(VARCHAR(256), lasttime, 120) from forum where Forum ='" & forumname & "'  And Auther = '" & name & "' order by lasttime"
            theres = cmd.ExecuteScalar()
            Return theres
        Catch ex As Exception
            Throw ex
        Finally
            con.Close()
        End Try
    End Function

    Shared Function lastpostmade(ByVal name As String, ByVal forumname As String, ByVal title As String) As Date
        Dim con As New SqlConnection(local)
        Dim cmd As New SqlCommand
        cmd.Connection = con
        Try
            con.Open()
            Dim theres As Date
            cmd.CommandText = "Select TOP 1  lasttime from forum where Forum ='" & forumname & "' and Title = '" & title & "' And Auther = '" & name & "' order by lasttime desc"
            theres = cmd.ExecuteScalar()
            Return theres
        Catch ex As Exception
            Throw ex
        Finally
            con.Close()
        End Try
    End Function
    Shared Function lastpost(ByVal title As String) As Results
        Dim con As New SqlConnection(local)
        Dim cmd As New SqlCommand
        cmd.Connection = con
        cmd.Parameters.AddWithValue("@title", title)
        Try
            con.Open()
            Dim Res As Results
            cmd.CommandText = "Select CAST(noviews AS VARCHAR(256)) From forum where Title =@title and numrep = 0"
            Res.Result1 = cmd.ExecuteScalar()
            cmd.CommandText = "Select Count(*) From forum where Title =@title and numrep <> 0 "
            Res.Result2 = cmd.ExecuteScalar()
            cmd.CommandText = "Select  title +'|'+ LastPoster +'|'+ CONVERT(VARCHAR(256), lasttime, 120) + '|'+ CAST(ID AS VARCHAR(256)) +'|'+ CAST(numrep AS VARCHAR(256)) from forum where Title =@title order by lasttime DESC"
            Res.Result3 = cmd.ExecuteScalar()
            Return (Res)
        Catch ex As Exception
            Throw ex
        Finally
            con.Close()
        End Try
    End Function



    Shared Function countpostpage(ByVal ID As Integer, ByVal title As String) As Integer
        Dim con As New SqlConnection(local)
        Dim cmd As New SqlCommand
        cmd.Connection = con
        Try
            con.Open()
            Dim theres As Integer
            cmd.Parameters.AddWithValue("@title", title)
            cmd.CommandText = "select count(*) from forum where Title=@title and ID <= ID"
            theres = cmd.ExecuteScalar()
            Return theres
        Catch ex As Exception
            Throw ex
        Finally
            con.Close()
        End Try
    End Function

    Shared Function noposts(ByVal forumname As String) As Integer
        Dim con As New SqlConnection(local)
        Dim cmd As New SqlCommand
        cmd.Connection = con
        Try
            con.Open()
            cmd.CommandText = "Select Count(*) From nousersonline where PageUrl like @forumname and (ActivityDate BETWEEN DATEADD(n, -5, getdate()) and getdate())"
            cmd.Parameters.AddWithValue("@forumname", "%" & forumname & "%")
            Dim Res As Integer
            Dim o As Object = cmd.ExecuteScalar()
            If IsDBNull(o) = False Then
                Res = o
            Else
                Res = 0
            End If
            Return Res
        Catch ex As Exception
            Throw ex
        Finally
            con.Close()
        End Try
    End Function

    Shared Function usersonpage(ByVal forumname As String) As List(Of String)
        Dim con As New SqlConnection(local)
        Dim cmd As New SqlCommand
        cmd.Connection = con
        Try
            con.Open()
            cmd.CommandText = "Select Username from  nousersonline where PageUrl like @forumname and (ActivityDate BETWEEN DATEADD(n, -5, getdate()) and getdate())"
            cmd.Parameters.AddWithValue("@forumname", "%" & forumname & "%")
            Dim MyDataReader As System.Data.SqlClient.SqlDataReader
            MyDataReader = cmd.ExecuteReader()
            Dim Res As New List(Of String)
            While MyDataReader.Read
                Res.Add(MyDataReader.Item(0))
            End While
            Return Res
        Catch ex As Exception
            Throw ex
        Finally
            con.Close()
        End Try

    End Function

    Shared Function Useronline(ByVal Username As String) As String
        Dim con As New SqlConnection(local)
        Dim cmd As New SqlCommand
        cmd.Connection = con
        Try
            con.Open()
            Dim theres As String
            cmd.CommandText = "Select Username from nousersonline where Username = '" & Username & "'AND (ActivityDate BETWEEN DATEADD(n, -5, getdate()) and getdate())"
            theres = cmd.ExecuteScalar()
            Return theres
        Catch ex As Exception
            Throw ex
        Finally
            con.Close()
        End Try
    End Function

    Shared Function thequote(ByVal id As Integer) As String
        Dim con As New SqlConnection(local)
        Dim cmd As New SqlCommand
        cmd.Connection = con
        Try
            con.Open()
            Dim theres As String
            cmd.CommandText = "Select Auther + '|'+ Post + '|'+ CONVERT(VARCHAR(256), lasttime, 120) + '|'+ Forum + '|'+ Title from forum where ID = " & id & " "
            theres = cmd.ExecuteScalar()
            Return theres
        Catch ex As Exception
            Throw ex
        Finally
            con.Close()
        End Try
    End Function
End Class

Open in new window



commented code out in areas so i can fix this issue
0
What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
LVL 74

Expert Comment

by:käµfm³d 👽
ID: 36516792
Which line is raising the error?
0
 

Author Comment

by:runnerjp2005
ID: 36516841
lastrep.Text = res.Result3.Split("|")(1)
0
 
LVL 74

Accepted Solution

by:
käµfm³d   👽 earned 500 total points
ID: 36516886
Set a breakpoint at that line and see if either res or res.Result3 is null. You can do this by going into the Immediate Window (Ctrl-Alt-I) and entering something like:

?res

Open in new window


and

?res.Result3

Open in new window


You will either see a response of "Nothing" indicating null-ness, or you will see information about the object. My guess is that one of those calls will show "Nothing".
0
 

Author Comment

by:runnerjp2005
ID: 36529145
res itself gives me nothing....

so is it the call 2 results that is not working???

btw thankls for that tip as its very quick in finidng errors!!!
0

Featured Post

Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

Join & Write a Comment

The ECB site provides FX rates for major currencies since its inception in 1999 in the form of an XML feed. The files have the following format (reducted for brevity) (CODE) There are three files available HERE (http://www.ecb.europa.eu/stats/exch…
If you need to start windows update installation remotely or as a scheduled task you will find this very helpful.
This video discusses moving either the default database or any database to a new volume.
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…

707 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

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now