根据下拉列表中的"Other“选项,我想将标签和文本框添加到<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我一直收到一个未处理的异常,声明object reference未设置为对象的实例。
我遗漏了什么?
发布于 2011-12-03 09:52:05
如果你的<p>-tag是runat=server,你应该能够在-file后面的代码中直接引用它。给它一个ID deptPtag,然后在signer.vb文件中自动生成:
Protected WithEvents deptPtag As Global.System.Web.UI.HtmlControls.HtmlGenericControl但您还必须确保在每次回发时都会重新创建动态控件( Page_Load中的最新版本,重新加载ViewState的事件为时已晚)。否则你将无法读取deptTb.Text或处理它的TextChanged-event。每次回发的ID必须相同,才能正确加载ViewState。
我在this question上的回答解释了你的NullReferenceException。这是FindControl在母版页内容页中的一种特殊行为。
https://stackoverflow.com/questions/8364770
复制相似问题