Go Premium for a chance to win a PS4. Enter to Win

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

null reference exception

Hi Everyone,

I have a User Control that I want to be able to call a Save function from a separate User Control.

So for instance, the User Control (Header) is a form that sits on a page. The page contains a second User Control which has a button called save. When the button Save is clicked it will save all the fields in the Header.


Here's my code:

 Public Sub Save()
       Dim InspectionDate As String = CType(Page.FindControl("InspectionDate"), TextBox).Text()
       Dim Inspector As String = CType(Page.FindControl("Inspector"), TextBox).Text()

     ' Write the fields to the database
end sub

The problem I have is that when I call the save function is that the fields I try to access, I get a null reference exception : Object reference not set to an instance of an object.

[NullReferenceException: Object reference not set to an instance of an object.]
   HousingWebsite.HousingInspectionHeader.Save() in C:\Inetpub\wwwroot\HousingWebsite\Modules\HousingInspection\HousingInspectionHeader.ascx.vb:314
   HousingWebsite.Bathrooms.lstMyDataList_UpdateCommand(Object source, DataListCommandEventArgs e) in C:\Inetpub\wwwroot\HousingWebsite\Modules\HousingInspection\Bathrooms.ascx.vb:203
   System.Web.UI.WebControls.DataList.OnUpdateCommand(DataListCommandEventArgs e) +109
   System.Web.UI.WebControls.DataList.OnBubbleEvent(Object source, EventArgs e) +294
   System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args) +26
   System.Web.UI.WebControls.DataListItem.OnBubbleEvent(Object source, EventArgs e) +100
   System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args) +26
   System.Web.UI.WebControls.LinkButton.OnCommand(CommandEventArgs e) +121
   System.Web.UI.WebControls.LinkButton.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +115
   System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +18
   System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +138
   System.Web.UI.Page.ProcessRequestMain() +1277


Any help would be appreciated. Thanks!
0
mance
Asked:
mance
  • 9
  • 8
1 Solution
 
David H.H.LeeCommented:
mance,
Try to change the different name instead of same name with object's name.

Regards
x_com
0
 
manceAuthor Commented:
x_com thanks for the quick response, but I'm not sure what you mean?

Do you mean, create a new TextBox and bind using the FindControl?

e.g. Dim mytextbox As TextBox = CType(Page.FindControl("InspectionYear"), TextBox)

Thanks.
0
 
David H.H.LeeCommented:
mance ,
What i mean is use different variable name (can't same with object name)
eg:
Dim InspectionDate As String = CType(Page.FindControl("InspectionDate"), TextBox).Text()

Change to
Dim ispDate As String = CType(Page.FindControl("InspectionDate"), TextBox).Text()
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
manceAuthor Commented:
Hi x_com,

Thanks for the advice but I still get the null reference exception. I think it's due to the fact that the Page does not contain any controls. I constructed a For Loop to print out all the IDs on the form and all I got was the FormID - no other items or controls.

I'm guess that this means the page has not been instianted??? Not sure how to get around this issue.
0
 
David H.H.LeeCommented:
mance ,
can you post the related code here?
0
 
David H.H.LeeCommented:
mance ,
make sure you assign an special id for each control you're built.
'when you build the control in every literations :

Dim  InspectionDate as As New System.Web.UI.WebControls.TextBox()
n=10
For i=1 to n
  InspectionDate.iD="txt" & i
  txtBoxes.Controls.Add(InspectionDate)
Next

-make sure you're access the correct object.

Regards
x_com
0
 
manceAuthor Commented:
Hi X_Com,

The Code is kinda involved ... but here goes.

I have a page which Contains several User Controls. The User Control Bathrooms.ascx has a reference to the User Control HousingInspectionHeader.aspx (actually the HousingInspectionHeader is the parent to Bathrooms.ascx because based on what the user selects the Header will always be the same. The Header will also determine what subform to load ... ie Bathrooms, Kitchen, etc .. ). When the User clicks on the Save button contained in Bathrooms.ascx, the event will call a Function in HousingInspectionHeader to Save all the Information in the Header form.


Here's the code Snippet:

**** Bathroom.ascx ******

Protected myHousingInspectionHeader As HousingInspectionHeader

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        myHousingInspectionHeader = Page.FindControl("HousingInspectionModule")
        If Me.IsPostBack = False Then
            Dim reader As IDataReader = GetDataReader(strSQL)
            BindGrid(reader)
        End If

 End Sub

 Private Sub lstMyDataList_UpdateCommand(ByVal source As Object, ByVal e As DataListCommandEventArgs) Handles lstMyDataList.UpdateCommand

   ' Code to update lstMyDataList

   myHousingInspectionHeader.Save()

 End Sub

   **** End Bathroom.ascx ******



**** HousingInspectionHeader.ascx ******

    Protected WithEvents lstHousingInspectionHeader As System.Web.UI.WebControls.DataList
    Protected WithEvents InspectionYear As System.Web.UI.WebControls.TextBox
    Protected WithEvents InspectionDate As System.Web.UI.WebControls.TextBox
    Protected WithEvents Inspector As System.Web.UI.WebControls.TextBox


   Public Sub Save()

        Dim InspectionDate As String = CType(Page.FindControl("InspectionDate"), TextBox).Text()
       Dim Inspector As String = CType(Page.FindControl("Inspector"), TextBox).Text()

       'Update fields
       
    End Sub

hope that's clear .... thanks for the help!
0
 
David H.H.LeeCommented:
mance ,
I saw you have 2 decalarations with Same variables name. changes it now!
Eg:

Protected WithEvents InspectionDate As System.Web.UI.WebControls.TextBox
Protected WithEvents Inspector As System.Web.UI.WebControls.TextBox

Dim InspectionDate As String = CType(Page.FindControl("InspectionDate"), TextBox).Text()
Dim Inspector As String = CType(Page.FindControl("Inspector"), TextBox).Text()

change to
Protected WithEvents InspectionDate As System.Web.UI.WebControls.TextBox
Protected WithEvents Inspector As System.Web.UI.WebControls.TextBox

Dim InspDate As String = CType(Page.FindControl("InspectionDate"), TextBox).Text()
Dim Insp As String = CType(Page.FindControl("Inspector"), TextBox).Text()

Besides that, do show me which line the error happed in VS.NET environmanet:
Eg:
22. AAAAA
23. XXXX <------This line
24. BBBB

Give me more details about the error. And, you also need to tell me when you assign the new id for each control.

0
 
manceAuthor Commented:
Hi x_com,

Changed the variable name has no effect ... this is the error.

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 291:
Line 292:
Line 293:        Dim InspDate As String = CType(Page.FindControl("InspectionDate"), TextBox).Text()
Line 294:        Dim Insp As String = CType(Page.FindControl("Inspector"), TextBox).Text()
Line 295:
 

Source File: C:\Inetpub\wwwroot\HousingWebsite\Modules\HousingInspection\HousingInspectionHeader.ascx.vb    Line: 293

Stack Trace:


[NullReferenceException: Object reference not set to an instance of an object.]
   HousingWebsite.HousingInspectionHeader.Save() in C:\Inetpub\wwwroot\HousingWebsite\Modules\HousingInspection\HousingInspectionHeader.ascx.vb:293
   HousingWebsite.Bathrooms.lstMyDataList_UpdateCommand(Object source, DataListCommandEventArgs e) in C:\Inetpub\wwwroot\HousingWebsite\Modules\HousingInspection\Bathrooms.ascx.vb:205
   System.Web.UI.WebControls.DataList.OnUpdateCommand(DataListCommandEventArgs e) +109
   System.Web.UI.WebControls.DataList.OnBubbleEvent(Object source, EventArgs e) +294
   System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args) +26
   System.Web.UI.WebControls.DataListItem.OnBubbleEvent(Object source, EventArgs e) +100
   System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args) +26
   System.Web.UI.WebControls.LinkButton.OnCommand(CommandEventArgs e) +121
   System.Web.UI.WebControls.LinkButton.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +115
   System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +18
   System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +138
   System.Web.UI.Page.ProcessRequestMain() +1277

 
0
 
David H.H.LeeCommented:
mance ,
I also want to see when you assign the id for each control. Post it here.
0
 
manceAuthor Commented:
     <asp:datalist id="lstHousingInspectionHeader" Runat="server" CssClass="GeneralContent" Width="100%">
      
<EditItemTemplate>
                                                <table class='TextPrint' border="0" width='100%' cellspacing="3" cellpadding="2">
                                                      <tr>
                                                            <td valign="top" colspan="2" class="InspectionHeaderDetailsCell">Inspector
                                                                  (Last,First):</td>
                                                            <td colspan="2">
                                                                  <asp:textbox id="Inspector" text='<%# Container.DataItem("Inspector")%>' runat=server CssClass="InspectionEstimatedCost" maxlength="50" />
                                                            </td>
                                                      </tr>
                                                      <tr>
                                                            <td valign="top" class="InspectionHeaderDetailsCell">Inspection Year:</td>
                                                            <td>
                                                                  <asp:textbox id="InspectionYear" text='<%# Container.DataItem("InspectionYear")%>' runat=server CssClass="InspectionEstimatedCost" maxlength="50" />
                                                            </td>
                                                            <td valign="top" class="InspectionHeaderDetailsCell">Inspection Date:</td>
                                                            <td>
                                                                  <asp:textbox id="InspectionDate" text='<%# DataBinder.Eval(Container.DataItem, "InspectionDate", "{0:d}")%>' runat=server CssClass="InspectionEstimatedCost" maxlength="50" />
                                                            </td>
                                                      </tr>
                                                      <tr>
                                                            <td valign="top" colspan="2" class="InspectionHeaderDetailsCell"><b>Inspection Total: </b>
                                                            </td>
                                                            <td colspan="2">
                                                                  <input id=TotalEstimatedCost value='<%# DataBinder.Eval(Container.DataItem, "TotalEstimatedCost", "{0:C}") %>' Class=InspectionEstimatedCost maxlength=10 readOnly />
                                                            </td>
                                                      </tr>
                                                </table>
                                          </EditItemTemplate>
                                    </asp:datalist>




The Items are actually contained within a DataList ... which probably poses some of the problems. But I've tried various methods of trying to get at the datalist or the items and all have resulted in the Null Reference Exception.

For Instance, when I try to iterate through the DataList, I get only one item.

Code:

    Dim myHIModule As HousingInspectionHeader = Parent.FindControl("HousingInspectionModule")
        Dim myHIList As DataList = Parent.FindControl("HousingInspectionModule").FindControl("lstHousingInspectionHeader")

        Dim sizeDataList As Integer = myHIHeader.Controls.Count

        For i = 0 To myHIHeader.Controls.Count -1
            strTempIDs = strTempIDs & "<BR>" & myHIHeader.Controls.Item(i).ID()
        Next

**** Produces nothing.

Trying to reference the item as follows :

 Dim tempString As String = CType(myHIHeader.FindControl("InspectionYear"), TextBox).Text

Produces null reference exception at that line.

I've also tried getting the control using the ID displayed when you go View Source: (

Dim tempString As String = CType(myHIHeader.FindControl("HousingInspectionModule_lstHousingInspectionHeader_ctl0_InspectionYear"), TextBox).Text

Same null reference exception.



Thanks for all your help ... I'll increase the point total and be sure to give at least partial marks for your help.
                              
0
 
David H.H.LeeCommented:
mance ,
I didnt saw you assign an id to each control. Just made a id for each control. Dont let system assign for you otherwise, you will get the same id. That's why you get only 1 item
Eg:
       For i = 0 To myHIHeader.Controls.Count -1
           myHIHeader.Controls.Item(i).ID="txt" & i <----------assign your own id
           strTempIDs = strTempIDs & "<BR>" & myHIHeader.Controls.Item(i).ID()
       Next

It's late for me to go to sleep now. I'll continue to help. You can post the latest problems here and let us to fix the problems

Regards
x_com
0
 
manceAuthor Commented:
Hi x_com,

I found the solution to my problem.

The issue was that I hadn't retrieved the proper object from the Page Collection. Since my User Controls are nested I have to first retrieve the User Control from the Page then from the User Control I had to retrieve the Datalist and then finally from the datalist I could retrieve the DataListItem (not the fields themselves).

What I was doing wrong was trying to perform a FindControl for InspectionYear on the DataList, when the only object the DataList contains at its root level is the DataListItem. If I were to perform the FindControl method using the DataListItem (the child of the DataList) then this would work.

Anyway, here's my code:


 Dim myHIModule As HousingInspectionHeader = Parent.FindControl("HousingInspectionModule")
        Dim myHIHeader As DataList = Page.FindControl("HousingInspectionModule").FindControl("lstHousingInspectionHeader")
        Dim myDLItem As System.Web.UI.WebControls.DataListItem = myHIHeader.Items(0)

        For i = 0 To myDLItem.Controls.Count - 1
            If TypeOf myDLItem.Controls(i) Is TextBox Then
                strTempIDs = strTempIDs & myDLItem.Controls.Item(i).ID() & " : " & CType(myDLItem.Controls.Item(i), TextBox).Text & "<BR>"
            End If
        Next

Anyway, thanks for your help ... I know I certainly wouldn't have wanted to piece what I wrote together!

I'm not sure how to reward points in this kind of situation, though?  Ideas?

Thanks!
0
 
manceAuthor Commented:
Ok Back Again ... there's still a problem!

The object that I referenced above does not contain the latest entries made by the User. The values are the values which were displayed. Therefore, any User updates made cannot be viewed. I'm not retrieving the values inputted by the user ... I'm grabbing the values which were displayed.

Any one know a solution to this?

I'm guessing we have to go the Request object????  

0
 
David H.H.LeeCommented:
mance ,
You always can refund if you'd find the answer by yourself. What you do is simply post a thread to request points refund at CS area. Admin will handle it.
For your last questions, possible somethings related with IsPostBack problems?Try to check again this problems.
0
 
manceAuthor Commented:
hi X_com,

Actually I found the solution ... and it really well unfortunately it doesn't really relate at all to the code that I had previously posted.

using context.response.item("NameofModule_NameofDatalist_ctl_ID") you can retrieve which ever field you wish. There may be some way of obtaining the values still through the Page Hierarchy. It'd be good to know if anyone has the answer.

Anyway, kinda went the long route to find this solution but it finally works!

Thanks for your help!
0
 
David H.H.LeeCommented:
Hi mance ,
Good info. to EE too. You can close it with Points refund at CS Area. Close it with points refund, dont delete!

Regards
x_com
0
 
NetminderCommented:
User resolved; points refunded and question closed.

Netminder
EE Admin
0

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

  • 9
  • 8
Tackle projects and never again get stuck behind a technical roadblock.
Join Now