我在ASPX页面中有2个用户控件。默认情况下,应禁用第二个用户控件。在该用户控件中,我只有一个文本框。所以我在页面加载事件中找到控件,如下所示:
TextBox txtLocation = (TextBox)PI_CompLocationTree.FindControl("txtLocation");
txtLocation.Enabled = false;
但我得到txtLocation为null。如何从ASCX控件获取ASPX页面中的控件?
我更新的代码..在Aspx页面..
<%@ Register Src="~/UserControl/PI_CompLocationTree.ascx" TagName="PI_CompLocationTree"
TagPrefix="uc1" %>
<div id="Div2">
<div class="location">
<div class="usLocation">
<uc1:PI_CompLocationTree ID="PI_CompLocationTree1" runat="server"/>
</div>
</div>
</div>
在页面加载中......
PI_CompLocationTree PI_CompLocationTree = new PI_CompLocationTree();
protected void Page_Init(object sender, EventArgs e)
{
var userControl = (PI_CompLocationTree)this.FindControl("PI_CompLocationTree1");
userControl.EnabledTextBox = false;
}
在ASCX页面中......
<asp:TextBox ID="txtLocation" CssClass="fadded_text fadded_text_ctrl" Style="width: 260px;
float: left;" runat="server" Text=""></asp:TextBox>
ASCX Code Behind ...
public partial class PI_CompLocationTree : System.Web.UI.UserControl
{
public bool EnabledTextBox
{
get { return txtLoc.Enabled; }
set { txtLoc.Enabled = value; }
}
}
答案 0 :(得分:2)
使用FindControl方法跟随..
1. UserControlClass objOfUserControl = (UserControlClass)Page.FindControl("UserControlID");
TextBox txtLocation= objOfUserControl.FindControl("txtLocation");
txtLocation.Enabled = false;
2.您也可以使用公共财产跟随
在用户控制代码隐藏中
public bool TextBoxUSC
{
set{txtLocation.Enabled = value;}
}
在Aspx代码背后
UserControlClass.TextBoxUSC=false;
如果您使用母版页
ContentPlaceHolder cph = (ContentPlaceHolder)this.Page.Master.FindControl("MainContent");//"MainContent" is ContentPlaceHolder's ID
UserControlClass userCntrl = (UserControlClass)cph.FindControl("UserControlID");
userCntrl.TextBoxUSC = false;
答案 1 :(得分:1)
试试这个
<强>被修改强>
在aspx中设置Enabled
false
,你可以这样做:
向您的UC添加属性:
public bool EnabledTextBox
{
get{return IdTextBox.Enabled;}
set{IdTextBox.Enabled=value;}
}
然后在aspx中:
IdOfYourUserControlWithProperty.EnabledTextBox = false;
希望有所帮助
答案 2 :(得分:0)
罗宾你可以删除
TextBox txtLocation = (TextBox)PI_CompLocationTree.FindControl("txtLocation");
txtLocation.Enabled = false;
在您的aspx中,使用runat =“server”
添加表单也删除
PI_CompLocationTree PI_CompLocationTree = new PI_CompLocationTree();
您不需要因为使用FindControl
你的工作很好
答案 3 :(得分:0)
PI_CompLocationTree1.EnabledTextBox = false; //from .aspx page. There's no need to use FindControl if you've added it statically to the webpage.