0

Based on a choice of "Other" in a dropdown I want to add a label and textbox to a <p> tag. I have added runat=server in the <p> tag.

    Protected Sub deptDdl_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles deptDdl.SelectedIndexChanged
        'If the user chooses other for the department type add
        'a label and textbox to allow them to fill in a department not listed

        If deptDdl.SelectedValue.ToString = "Other" Then
            Dim deptLbl As Label = New Label
            deptLbl.Text = "Enter the Department Name"
            Dim deptTb As TextBox = New TextBox
            deptTb.MaxLength = 20

            Page.FindControl("m_ContentPlaceHolder1_deptPtag").Controls.AddAt(2, deptLbl)
            Page.FindControl("m_ContentPlaceHolder1_deptPtag").Controls.AddAt(3, deptTb)
        End If
    End Sub

I keep getting an unhandled exception stating Object reference not set to an instance of an object.

What am I missing?

Ry-
  • 218,210
  • 55
  • 464
  • 476
Pete
  • 179
  • 1
  • 2
  • 7
  • Tip: You don't need `As X = New X`. You can just do `As New X`. So `Dim deptLbl As New Label()` for example. – Ry- Dec 03 '11 at 01:34

1 Answers1

1

If your <p>-tag is runat=server you should be able to reference it in the codebehind -file directly. Give it an ID deptPtag, then this should be autogenerated in the designer.vb-file:

Protected WithEvents deptPtag As Global.System.Web.UI.HtmlControls.HtmlGenericControl

But you also have to ensure that your dynamic controls are recreated on every postback(latest in Page_Load, events are too late for reloading the ViewState). Otherwise you won't be able to read deptTb.Text or handle it's TextChanged-event. The ID must be the same on every postback to correctly load the ViewState.

My answer on this question explains your NullReferenceException. It's a special behaviour of FindControl from within a MasterPage's content-page.

Community
  • 1
  • 1
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939