[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

object reference null when trying to reference a control inside a user control

Posted on 2006-05-23
15
Medium Priority
?
501 Views
Last Modified: 2007-12-19
I am trying to create a User Control, that will be a message box with input options

if I call okconf.visible = true in the page load of the user control it works fine, but if i then try to call it later by calling the user controls alert method i get a reference null error.

heres the class code

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Public Class AlertBox1
    Inherits System.Web.UI.UserControl

#Region " Web Form Designer Generated Code "

    'This call is required by the Web Form Designer.
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

    End Sub
    Protected WithEvents btnOk As System.Web.UI.WebControls.Button
    Protected WithEvents okconf As System.Web.UI.HtmlControls.HtmlGenericControl
    Protected WithEvents oktitle As System.Web.UI.HtmlControls.HtmlGenericControl
    Protected WithEvents okmsg As System.Web.UI.HtmlControls.HtmlGenericControl
    Protected WithEvents btnYes As System.Web.UI.WebControls.Button
    Protected WithEvents btnNo As System.Web.UI.WebControls.Button

    'NOTE: The following placeholder declaration is required by the Web Form Designer.
    'Do not delete or move it.
    Private designerPlaceholderDeclaration As System.Object

    Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
        'CODEGEN: This method call is required by the Web Form Designer
        'Do not modify it using the code editor.
        InitializeComponent()
    End Sub

#End Region

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'Put user code to initialize the page here
        okconf.Visible = False
    End Sub
    Public Enum msgType
        okMsg
        YesNo
    End Enum

    Public Sub alert(ByVal MsgText As String, ByVal msgTitle As String, Optional ByVal OKMethod As String = "", Optional ByVal AlertType As msgType = msgType.okMsg, Optional ByVal YesMethod As String = "", Optional ByVal NoMethod As String = "")
        Select Case AlertType
            Case Is = msgType.okMsg
                okconf.Visible = True
                btnYes.Visible = False
                btnNo.Visible = False
                btnOk.Visible = True
                Session("OKProc") = OKMethod
                okmsg.InnerHtml = MsgText
                oktitle.InnerHtml = msgTitle
                okconf.Style.Item("left") = 300
                okconf.Style.Item("TOP") = 300

                'focus ok button
                Page.RegisterStartupScript("CallSetFocus", "<SCRIPT language=javascript>GetElementByName('btnOk').focus();</SCRIPT>")

            Case Is = msgType.YesNo
                okconf.Visible = True
                btnYes.Visible = True
                btnNo.Visible = True
                btnOk.Visible = False
                Session("YProc") = YesMethod
                Session("NProc") = NoMethod
                Session("YNAns") = ""
                okmsg.InnerHtml = MsgText
                oktitle.InnerHtml = msgTitle
                okconf.Style.Item("left") = 300
                okconf.Style.Item("TOP") = 200

                'Focus Yes Button
                Page.RegisterStartupScript("CallSetFocus", "<SCRIPT language=javascript>GetElementByName('btnYes').focus();</SCRIPT>")
        End Select

 
    End Sub
End Class

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
heres the code behind for the main page

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'Put user code to initialize the page here

        Dim alert As New AlertBox1
        alert.alert("a message in the box", "a msg title", , AlertBox1.msgType.okMsg)


End Sub


so it crashes on the user control code behind when it tries to set okconf.visible to true
0
Comment
Question by:o0JoeCool0o
  • 5
  • 5
  • 3
13 Comments
 

Expert Comment

by:big1975foot
ID: 16746881
In the NEW method of the control, you can set the following:

        Public Sub New()
            btnOk = New System.Web.UI.WebControls.Button
            okconf = New System.Web.UI.HtmlControls.HtmlGenericControl
            oktitle = New System.Web.UI.HtmlControls.HtmlGenericControl
            okmsg = New System.Web.UI.HtmlControls.HtmlGenericControl
            btnYes = New System.Web.UI.WebControls.Button
            btnNo = New System.Web.UI.WebControls.Button
        End Sub
0
 
LVL 4

Author Comment

by:o0JoeCool0o
ID: 16746911
Ok it looks like is passing that point and now hanging on

 Session("OKProc") = OKMethod
also giving a null reference error.

Does this mean I have to setup properties for the usercontrol for every string I want to reference regardless of whether I am declaring them in the methods paramaters?

Or am I doing something else wrong?

Sorry this is my first attempt at a user control
0
 
LVL 26

Expert Comment

by:Rejojohny
ID: 16749113
where have u loaded the user control? have u placed the user control in the test page during design time? if yes, what is the name of the control .. use that and do not initialize a new "alertbox" object .. when u do that ,, all the control in that usercontrol is not created as the controls etc are only loaded in the init event of the user control and that is the reason y u get the error ..

Rejo
0
Independent Software Vendors: 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!

 

Expert Comment

by:big1975foot
ID: 16750969
In order to access the SESSION object outside of your main page (such as in the code behind a user control), you can use SYSTEM.WEB.HTTPCONTEXT.CURRENT.SESSION versus just using SESSION. So, in the example you cited, you may wish to use System.Web.Httpcontext.Current.Session.Add("okProc", YesMethod) to add the value and System.Web.Httpcontext.Current.Session.Item("okProc") to access the value.
0
 

Expert Comment

by:big1975foot
ID: 16750990
Sorry, I meant System.Web.Httpcontext.Current.Session.Add("okProc", OKMethod) to add the value
0
 
LVL 4

Author Comment

by:o0JoeCool0o
ID: 16751636
Yes I dragged it on to the test page at design time, and its name is AlertBox1

Now if I try referencing it like AlertBox1. the intellitext pop up only pops up msgtype, and not the alert event as an option.
Unless I Dim AB as new AlertBox1
then when i type AB. I get the full options of AlertBox1 including the Alert Method that im after.

Anyway the session thing you mentioned was the culprit and it is now hanging on

Page.RegisterStartupScript("CallSetFocus", "<SCRIPT language=javascript>GetElementByName('btnOk').focus();</SCRIPT>")
as yet again a null reference error.

What is with the null reference error you would think they would have done a better job at the error handling in a user control.

this is getting frustrating!

>>>>>>>>>>>>>>>>>>>>
where have u loaded the user control? have u placed the user control in the test page during design time? if yes, what is the name of the control .. use that and do not initialize a new "alertbox" object .. when u do that ,, all the control in that usercontrol is not created as the controls etc are only loaded in the init event of the user control and that is the reason y u get the error ..
0
 
LVL 4

Author Comment

by:o0JoeCool0o
ID: 16752898
ok if I take out the Page.RegisterStartupScript and run it (wanted to see if the otehr stuff was actually working) it doesnt actually work

okconf.visible is being called and not crashing but the DIV with Id "okconf" that I have placed on the user Control design ascx page does not become visible.
0
 

Expert Comment

by:big1975foot
ID: 16752976
I don't believe the Page object is accessible in this context (There may be a way, but I'm not sure how). One option is to pass in the Page object from your base page and use the reference to access it's methods.
0
 
LVL 4

Author Comment

by:o0JoeCool0o
ID: 16752988
ok so what do I do about the objects on the user control not actually being referenced in the method? its like the only time you can access those web elements is at the intitialization of the user control and once its initialized its static and cannot change... doesnt that defeat the purpose of having a user control"?
0
 

Expert Comment

by:big1975foot
ID: 16753022
Sorry I can't be of more assistance, but my experience with user controls is limited as I have been primarily working with composite controls in my development.
0
 
LVL 26

Expert Comment

by:Rejojohny
ID: 16757850
>>I don't believe the Page object is accessible in this context
It is accessible from user control

>>Now if I try referencing it like AlertBox1. the intellitext pop up only pops up msgtype,
u could try locating the control alertbox1 and change the type to reference its properties .. something like this
Dim x as AlertBox = ctype(me.findControls("AlertBox1"), Alertbox)

>>ok so what do I do about the objects on the user control not actually being referenced in the method? its like the only time you can access those web elements is at the intitialization of the user control and once its initialized its static and cannot change
that not so .. u can change the values of the controls of the user control ..  If i remember correct, i think to change values in the user control, u might need to expose properties and handle it within that code ..

these links might also be of some help on how to create and consume a user control ..
http://www.asp101.com/lessons/usercontrols.asp
http://www.15seconds.com/issue/020319.htm

as u can see the controls are accesed in the page events too ..
0
 
LVL 4

Author Comment

by:o0JoeCool0o
ID: 16761466
>> u could try locating the control alertbox1 and change the type to reference its properties .. something like this
Dim x as AlertBox = ctype(me.findControls("AlertBox1"), Alertbox)

I tried this and it tells me findcontrols is not a member of 'MasterControl.test' (my aspxpage)

>>that not so .. u can change the values of the controls of the user control ..  If i remember correct, i think to change values in the user control, u might need to expose properties and handle it within that code ..

My ultimate goal here is to not have to expose public properties to call my method
I want to be able to call my method like
alertbox.alert("Message", "Title")
rather then alertbox.message = message alertbox.title = title

>>these links might also be of some help on how to create and consume a user control ..
I have read these pages and they do not offer any example on using a custom method.
They too are using properties to set the variables rather then having them be passed in as parameters.
As well they are using codebehind on the subcontrols themselves. which I assume is why they can access them.

thank you for helping me with this
0
 
LVL 26

Accepted Solution

by:
Rejojohny earned 2000 total points
ID: 16766408
>>Yes I dragged it on to the test page at design time, and its name is AlertBox1
I hope u have the declaration statement on the top for alertbox1 in code behind

>>I tried this and it tells me findcontrols is not a member of 'MasterControl.test' (my aspxpage)
try ... Dim x as AlertBox = ctype(Page.FindControl("AlertBox1"), Alertbox) in page_load .. Findcontrols should work .. page does have a member called "FindControl" ...

more examples

This one should solve ur problem
http://www.dotnetjunkies.com/Article/1DC595C5-B34D-432B-B78E-93FFEF1FC2FE.dcik
http://www.dotnetjunkies.com/tutorial/3443CE54-E56C-476F-88A2-5F811A79880C.dcik

MSDN example
http://aspalliance.com/quickstart/aspplus/doc/webpagelets.aspx

http://aspalliance.com/67
http://aspnet.4guysfromrolla.com/articles/031704-1.aspx
dynamically adding a user control
http://www.codeproject.com/aspnet/aspnetusercontrol2.asp

Notify One Control Of Changes In Other Control
http://www.codeproject.com/aspnet/ASPNetUserControl3.asp

Creating a Login User Control
http://www.c-sharpcorner.com/Security/LoginUserControl.asp
http://authors.aspalliance.com/aspxtreme/webforms/userctrls/creatingpageletcontrol.aspx

Creating Reusable Content in ASP.NET
http://www.samspublishing.com/articles/article.asp?p=173411&rl=1
0

Featured Post

Independent Software Vendors: 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

Today is the age of broadband.  More and more people are going this route determined to experience the web and it’s multitude of services as quickly and painlessly as possible. Coupled with the move to broadband, people are experiencing the web via …
A quick way to get a menu to work on our website, is using the Menu control and assign it to a web.sitemap using SiteMapDataSource. Example of web.sitemap file: (CODE) Sample code to add to the page menu: (CODE) Running the application, we wi…
Is your OST file inaccessible, Need to transfer OST file from one computer to another? Want to convert OST file to PST? If the answer to any of the above question is yes, then look no further. With the help of Stellar OST to PST Converter, you can e…
As many of you are aware about Scanpst.exe utility which is owned by Microsoft itself to repair inaccessible or damaged PST files, but the question is do you really think Scanpst.exe is capable to repair all sorts of PST related corruption issues?
Suggested Courses
Course of the Month19 days, 21 hours left to enroll

873 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