【问题标题】:SelectedIndex add controlsSelectedIndex 添加控件
【发布时间】:2012-01-11 23:32:15
【问题描述】:

基于在下拉列表中选择“其他”,我想将标签和文本框添加到 <p> 标记。我在<p> 标签中添加了runat=server

    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

我不断收到未处理的异常,指出未将对象引用设置为对象的实例。

我错过了什么?

【问题讨论】:

  • 提示:您不需要As X = New X。你可以做As New X。以Dim deptLbl As New Label() 为例。

标签: asp.net vb.net drop-down-menu


【解决方案1】:

如果您的<p>-tag 是runat=server,您应该可以直接在代码隐藏文件中引用它。给它一个 ID deptPtag,然后它应该在 Designer.vb 文件中自动生成:

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

但您还必须确保在每次回发时重新创建动态控件(最新的 Page_Load,事件对于重新加载 ViewState 来说太迟了)。否则你将无法读取deptTb.Text 或处理它的TextChanged-event。 每次回发的 ID 必须相同才能正确加载 ViewState

我在this question 上的回答解释了您的NullReferenceException。 这是 MasterPage 的内容页面中 FindControl 的一种特殊行为。

【讨论】:

    猜你喜欢
    • 2020-04-05
    • 1970-01-01
    • 2012-12-21
    • 2014-03-21
    • 1970-01-01
    • 1970-01-01
    • 2013-12-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多