0

我在用户控件表单上有一个字段“x”,它包含在 aspx 页面和使用 SharePoint 母版页的页面上。我试图在我的代码中的 aspx 页面上找到字段 x,但它会引发“未设置对象引用”错误。我已经尝试过,但没有任何效果,

((TextBox)Page.Master.FindControl("PlaceHolderMain").FindControl("Experience").FindControl("x")).Text


((TextBox)this.FindControl("x")).Text


((TextBox)Page.Master.FindControl("PlaceHolderMain").FindControl("x")).Text

我可以在页面源代码中找到该字段,

<input name="ctl00$PlaceHolderMain$ctl00$x" type="text" value="3" id="ctl00_PlaceHolderMain_ctl00_x" class="textbox" />

更新:-

以前我在 aspx 页面的加载事件上以编程方式添加用户控件,

UserControl uc = (UserControl)Page.LoadControl("Experience.ascx");
experineceForm.Controls.Add(uc);

但是通过查看页面源,我怀疑并考虑使用以下代码在设计时添加它,

<%@ Register TagPrefix="uc" TagName="Experience" Src="Experience.ascx" %>

<div id="experineceForm" runat="server">
   <uc:experience id="idExperienceForm" runat="server"/>
</div>

完成此操作后,我可以使用以下代码找到控件,

((TextBox)Page.Master.FindControl("PlaceHolderMain").FindControl("idExperienceForm").FindControl("txtEmployeeComments")).Text
4

2 回答 2

0

AFAIK,((TextBox)Page.Master.FindControl("x")).Text应该工作

于 2012-05-10T14:53:23.750 回答
0

试试这个函数(如下)对 ID 进行递归搜索。System.NullReferenceException: Object reference not set to an instance of an object错误很可能是因为脚本没有找到文本框,所以控件没有.Text属性。注意:root 将是包含您要查找的文本框的 asp.net 占位符对象或 asp.net 面板等的 id。在尝试使用控件之前,您应该测试是否返回 null。

public Control FindControlRecursive(Control root, string id)
{
    if (root.ID == id) {
        return root;
    }
    Control c = default(Control);
    foreach ( c in root.Controls) {
        Control t = FindControlRecursive(c, id);
        if ((t != null)) {
            return t;
        }
    }
    return null;
}
于 2012-05-11T09:10:56.530 回答