Object reference not set to an instance of an object.

Can someone help me find out why i'm receiving this error on the following line of code below? I'm also going to post all code for this page. I also have 2 UserControls that i'm calling within this page and if you need to see the code for the 2 UserControls then please let me know.

Public Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
       
        Dim GridView1 As CalvertGrade1 = DirectCast(Me.WebPartZone1.FindControl("WebPartGrade1"), CalvertGrade1)
        Dim GridView2 As CalvertGrade2 = DirectCast(Me.WebPartZone2.FindControl("WebPartGrade2"), CalvertGrade2)
        'Dim GridView1 As CalvertGrade1 = DirectCast(Me.WebPartZone1.FindControl("GridView1"), CalvertGrade1)
        'Dim GridView2 As CalvertGrade2 = DirectCast(Me.WebPartZone2.FindControl("GridView2"), CalvertGrade2)
         
        GridView1.DoWork1(CInt(Me.TextBox1.Text)) <--Object reference not set to an instance of an object
        GridView2.DoWork2(CInt(Me.TextBox1.Text))

End Sub
LVL 4
asp_net2Asked:
Who is Participating?
 
mkosbieCommented:
Think I finally got it.  The problem is that you cannot directly reference items in a WebPartsZone.  You need to search for them through the WebPartManager.  Here's an article explaining it, and some sample code (http://forums.asp.net/t/912900.aspx).


    Public Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
        Dim WebPartGrade1 As WebPart = WebPartManager1.WebParts("WebPartGrade1")
        Dim WebPartGrade2 As WebPart = WebPartManager1.WebParts("WebPartGrade2")
        
        Dim GridView1 As CalvertGrade1 = DirectCast(WebPartGrade1.Controls(0), CalvertGrade1)
        Dim GridView2 As CalvertGrade2 = DirectCast(WebPartGrade2.Controls(0), CalvertGrade2)
 
        GridView1.DoWork1(CInt(Me.TextBox1.Text))
        GridView2.DoWork2(CInt(Me.TextBox1.Text))
                   
    End Sub

Open in new window

0
 
RishadanPortCommented:
It means that an object, has not been declared, and is still intiailized as null.

So... in this case either, Me = null, or Me.TextBox1 = null, or Me.TextBox1.Text = null
0
 
RishadanPortCommented:
Or also GridView1 = null

All those cases could case that error on that line. So verify that
0
Cloud Class® Course: C++ 11 Fundamentals

This course will introduce you to C++ 11 and teach you about syntax fundamentals.

 
asp_net2Author Commented:
RishadanPort,

I'm not sure how to do this. I had someone help me with what i have now, but i still can't figure out what is causing this. I can say for sure that the value that i'm entering in my DB is in the table that i'm calling.
0
 
RishadanPortCommented:
Ok sorry, let me restate where the error could be occuring... there are multiple of places... each of which you should check.

GridView1.DoWork1(CInt(Me.TextBox1.Text))

1. GridView1 is null
2. Me.TextBox1 is null
3. Me.TextBox1.Text is null
4. Some variable accessed in the function CInt is null
5. Some variable accessed in the function DoWork1 is null

Use a debugger to step into the codes and find at what line specifically is causing the error
0
 
RishadanPortCommented:
Are you running your code in Visual Studio? If so, goto -->Debug-->Exceptions

Then check "Common Language Runtime Exceptions" to make the program break exactly when the error occurs so you can see at what line specifically it occured

Then run your application in debug mode, and it will now show you what line the error occured on
0
 
asp_net2Author Commented:
>> Use a debugger to step into the codes and find at what line specifically is causing the error

Not sure how to look for this. Can you explain so that i may understand, i'm still learning.
0
 
mkosbieCommented:
In Visual Studio, you can run the Debugger from the Debug menu, or by pressing F5 (make sure you have Debug="True" in your Page directive).  When the error hits, you'll be able to examine the variables in your Visual Studio window.  Look for one that's listed as null.
0
 
asp_net2Author Commented:
Yes i'm using Visual Studio 2008 standard edition and using VB.NET and ASP.NET 3.5. When i ran my code i went to Debug - Exceptions and pasted in my error and it said the following below.

An Exception containing the specified string was not found.
0
 
mkosbieCommented:
You don't want to go to exceptions.  That's where you manage how the debugger handles exceptions.  Instead, you want to execute the code in debug mode.  You can either do that by pressing F5 on the page you want to debug, or choosing "Debug | Start Debugging" on the page you want to debug.

When the page hits the "Object reference not set to an instance of an object" exception, it should automatically display the relevant code line in VS2008.  At the bottom of the window will be a variable list.  Examine each variable (GridView1 and Me.TextBox1) to make sure they aren't null.
0
 
asp_net2Author Commented:
When i run the code and look at the Locals tab i see GridView1 and GridView 2 = Nothing. Not sure how to correct this. It's driving me NUTS :(
0
 
asp_net2Author Commented:
Me.TextBox1.Text    "3218"    String
GridView 1 = Nothing
GridView 2 = Nothing
0
 
mkosbieCommented:
Alright, that means the lines: Me.WebPartZone1.FindControl("WebPartGrade1") and Me.WebPartZone1.FindControl("WebPartGrade2") are not finding the requested controls.  What kind of controls are WebPartZone1 and WebPartZone2?  Are there controls with the IDs WebPartGrade1 and WebPartGrade2 inside of them?

Post some of the code and we might be able to help more.
0
 
asp_net2Author Commented:
I'm going to post my 2 UserControls and my index.aspx page/code.

CalvertGrade1.ascx:

<%@ Control Language="VB" ClassName="CalvertGrade1" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<%@ Import Namespace="System.Data.SqlTypes" %>
<%@ Import Namespace="System.Configuration" %>
<%@ Import Namespace="System.Web.UI.WebControls" %>
<%@ Import Namespace="System.Web.UI.WebControls.WebParts.WebPart" %>

<script runat="server">
    Public Sub DoWork1(ByVal Text As Int32)
       
        Dim connectionString As String = ConfigurationManager.ConnectionStrings("PSSA").ConnectionString
        Dim conn As SqlConnection = New SqlConnection(connectionString)

        Dim dtGrade1 As DataTable = New DataTable()

        Dim gradeComm As SqlCommand
        gradeComm = New SqlCommand("WebPart1Test", conn)
        gradeComm.CommandType = CommandType.StoredProcedure
       
        ' Create Parameter for Querystring
        gradeComm.Parameters.Add("@stid", SqlDbType.Int)
        gradeComm.Parameters("@stid").Value = Text
       
        Dim adapter As SqlDataAdapter

        Try
            conn.Open()

            adapter = New SqlDataAdapter
            adapter.SelectCommand = gradeComm
            adapter.Fill(dtGrade1)
           
            GridView1.DataSource = dtGrade1
            GridView1.DataBind()
           
        Catch ex As Exception
           
        Finally
            conn.Close()
        End Try
    End Sub
</script>

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
    <Columns>
        <asp:BoundField DataField="STID" HeaderText="Student ID" />
        <asp:BoundField DataField="STFNAME" HeaderText="First Name" />
        <asp:BoundField DataField="STLNAME" HeaderText="Last Name" />
        <asp:BoundField DataField="CALVONEID" HeaderText="Calvert 1st Grade ID" />
    </Columns>
</asp:GridView>

0
 
asp_net2Author Commented:
CalvertGrade2.ascx:

<%@ Control Language="VB" ClassName="CalvertGrade2" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<%@ Import Namespace="System.Data.SqlTypes" %>
<%@ Import Namespace="System.Configuration" %>
<%@ Import Namespace="System.Web.UI.WebControls" %>
<%@ Import Namespace="System.Web.UI.WebControls.WebParts.WebPart" %>

<script runat="server">
    Public Sub DoWork2(ByVal Text As Int32)
       
        Dim connectionString As String = ConfigurationManager.ConnectionStrings("PSSA").ConnectionString
        Dim conn As SqlConnection = New SqlConnection(connectionString)

        Dim dtGrade2 As DataTable = New DataTable()
       
        Dim grade1Comm As SqlCommand
        grade1Comm = New SqlCommand("WebPart2Test", conn)
        grade1Comm.CommandType = CommandType.StoredProcedure
       
        ' Create Parameter for Querystring
        grade1Comm.Parameters.Add("@stid", SqlDbType.Int)
        grade1Comm.Parameters("@stid").Value = Text
       
        Dim adapter As SqlDataAdapter

        Try
            conn.Open()
           
            adapter = New SqlDataAdapter
            adapter.SelectCommand = grade1Comm
            adapter.Fill(dtGrade2)
           
            GridView2.DataSource = dtGrade2
            GridView2.DataBind()
           
        Catch ex As Exception

        Finally
            conn.Close()
        End Try
    End Sub
</script>

<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="false">
    <Columns>
        <asp:BoundField DataField="STID" HeaderText="Student ID" />
        <asp:BoundField DataField="STFNAME" HeaderText="First Name" />
        <asp:BoundField DataField="STLNAME" HeaderText="Last Name" />
        <asp:BoundField DataField="CALVTWOID" HeaderText="Calvert 2nd Grade ID" />
    </Columns>
</asp:GridView>
0
 
asp_net2Author Commented:
index.aspx:

<%@ Page Language="VB" Debug="True" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<%@ Import Namespace="System.Data.SqlTypes" %>
<%@ Import Namespace="System.Configuration" %>
<%@ Import Namespace="System.Web.UI.WebControls" %>
<%@ Import Namespace="System.Web.UI.WebControls.WebParts.WebPart" %>
<%@ Register Src="~/CalvertGrade1.ascx" TagName="CalvertGrade1" TagPrefix="uc1" %>
<%@ Register Src="~/CalvertGrade2.ascx" TagName="CalvertGrade2" TagPrefix="uc2" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
   
    Protected Sub DropDownList1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim wpDisplayMode As WebParts.WebPartDisplayMode = WebPartManager1.SupportedDisplayModes(DropDownList1.SelectedValue.ToString())
        WebPartManager1.DisplayMode = wpDisplayMode
    End Sub
   
    Protected Sub Page_Init(ByVal sender As Object, ByVal e As EventArgs)
        For Each wpMode As WebPartDisplayMode In WebPartManager1.SupportedDisplayModes
            Dim modeName As String = wpMode.Name
            Dim dd_ListItem As ListItem = New ListItem(modeName, modeName)
            DropDownList1.Items.Add(dd_ListItem)
        Next
    End Sub
   
    Public Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
       
        Dim GridView1 As CalvertGrade1 = DirectCast(Me.WebPartZone1.FindControl("WebPartGrade1"), CalvertGrade1)
        Dim GridView2 As CalvertGrade2 = DirectCast(Me.WebPartZone2.FindControl("WebPartGrade2"), CalvertGrade2)
 
        GridView1.DoWork1(CInt(Me.TextBox1.Text))
        GridView2.DoWork2(CInt(Me.TextBox1.Text))
                   
    End Sub

</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form2" runat="server">
    <asp:WebPartManager ID="WebPartManager1" runat="server" />
    <div>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:Button ID="Button1" runat="server" Text="Find Data" OnClick="Button1_Click" />
    <br />
        <asp:DropDownList ID="DropDownList1" AutoPostBack="true" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" runat="server"></asp:DropDownList>
    <br />
    <br />  
<asp:CatalogZone ID="CatalogZone1" runat="server">
    <ZoneTemplate>
        <asp:PageCatalogPart ID="Pagecatalogpart1" runat="server" />
    </ZoneTemplate>
</asp:CatalogZone>    
    <br />
<asp:EditorZone ID="EditorZone1" runat="server">
    <ZoneTemplate>
        <asp:AppearanceEditorPart ID="AppearanceEditorPart1" runat="server" />
    </ZoneTemplate>
</asp:EditorZone>
    <br />
    <br />
<asp:WebPartZone ID="WebPartZone1" runat="server" BorderColor="#CCCCCC" Font-Names="Verdana" Padding="6">
    <EmptyZoneTextStyle Font-Size="0.8em" />
    <PartStyle Font-Size="0.8em" ForeColor="#333333" />
    <TitleBarVerbStyle Font-Size="0.6em" Font-Underline="False" ForeColor="White" />
    <MenuLabelHoverStyle ForeColor="Yellow" />
    <MenuPopupStyle BackColor="#1C5E55" BorderColor="#CCCCCC" BorderWidth="1px" Font-Names="Verdana" Font-Size="0.6em" />
    <MenuVerbStyle BorderColor="#1C5E55" BorderStyle="Solid" BorderWidth="1px" ForeColor="White" />
    <PartTitleStyle BackColor="#1C5E55" Font-Bold="True" Font-Size="0.8em" ForeColor="White" />

    <ZoneTemplate>
      <uc1:CalvertGrade1 ID="WebPartGrade1" runat="server"></uc1:CalvertGrade1>
    </ZoneTemplate>      

    <MenuVerbHoverStyle BackColor="#E3EAEB" BorderColor="#CCCCCC" BorderStyle="Solid" BorderWidth="1px" ForeColor="#333333" />
    <PartChromeStyle BackColor="#E3EAEB" BorderColor="#C5BBAF" Font-Names="Verdana" ForeColor="#333333" />
    <HeaderStyle Font-Size="0.7em" ForeColor="#CCCCCC" HorizontalAlign="Center" />
    <MenuLabelStyle ForeColor="#333333" />
</asp:WebPartZone>  

    <br />
    <br />
     
<asp:WebPartZone ID="WebPartZone2" runat="server" BorderColor="#CCCCCC" Font-Names="Verdana" Padding="6">      
    <EmptyZoneTextStyle Font-Size="0.8em" />
    <PartStyle Font-Size="0.8em" ForeColor="#333333" />
    <TitleBarVerbStyle Font-Size="0.6em" Font-Underline="False" ForeColor="White" />
    <MenuLabelHoverStyle ForeColor="#E2DED6" />
    <MenuPopupStyle BackColor="#5D7B9D" BorderColor="#CCCCCC" BorderWidth="1px" Font-Names="Verdana" Font-Size="0.6em" />
    <MenuVerbStyle BorderColor="#5D7B9D" BorderStyle="Solid" BorderWidth="1px" ForeColor="White" />
    <PartTitleStyle BackColor="#5D7B9D" Font-Bold="True" Font-Size="0.8em" ForeColor="White" />

    <ZoneTemplate>
      <uc2:CalvertGrade2 ID="WebPartGrade2" runat="server"></uc2:CalvertGrade2>
    </ZoneTemplate>  

    <MenuVerbHoverStyle BackColor="#F7F6F3" BorderColor="#CCCCCC" BorderStyle="Solid" BorderWidth="1px" ForeColor="#333333" />
    <PartChromeStyle BackColor="#F7F6F3" BorderColor="#E2DED6" Font-Names="Verdana" ForeColor="White" />
    <HeaderStyle Font-Size="0.7em" ForeColor="#CCCCCC" HorizontalAlign="Center" />
    <MenuLabelStyle ForeColor="White" />
</asp:WebPartZone>  
   
    </div>
    </form>
</body>
</html>
0
 
RishadanPortCommented:
all I can say... is

ACK.
0
 
asp_net2Author Commented:
RishadanPort,

What do you mean by ACK?
0
 
asp_net2Author Commented:
mkosbie,

If you where close to me now i would give you A BIG HUG!!!! That worked, thank you.. thank you..
0
 
mkosbieCommented:
Glad to help.
0
 
asp_net2Author Commented:
mkosbie,

I only have a small problem when i run the code and that is i receive the following error below if a user doesn't enter an ID.

Conversion from string "" to type 'Integer' is not valid.
GridView1.DoWork1(CInt(Me.TextBox1.Text)) <---Conversion from string "" to type 'Integer' is not valid.
0
 
asp_net2Author Commented:
mkosbie,

Okay i was able to figure out how to handle the problem if a user does not enter ID and clicks button without an ID present. Please see what i have below and could you let me konw if this is the correct way?

If Me.TextBox1.Text = "" Then
            TextBox1.Text = ""
        Else
            GridView1.DoWork1(CInt(Me.TextBox1.Text))
            GridView2.DoWork2(CInt(Me.TextBox1.Text))
        End If
0
 
RishadanPortCommented:
You may get better response if you try breaking this up into different threads. Your original question was answered
0
 
asp_net2Author Commented:
Wow, thanks for nothing RishadanPort!
0
 
mkosbieCommented:
The way you're handling a blank ID will work to avoid a "Conversion from string..." error, but it won't do anything to inform you're user about the problem.  I would recommend using one of ASP.NETs built in validation controls (http://www.w3schools.com/aspnet/aspnet_refvalidationcontrols.asp) to confirm that the text box has an integer BEFORE firing the code.

Also, RishadanPort is technically correct, EE policy is that you put each question in its own thread.  I don't mind answering here, but generally you should try to split the questions up.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.