Web Control added in .master control type not found in child page
I have a Web Site project, and within it I have a user Web Control defined in an ascx file.
The con开发者_运维问答trol is added to the Site.Master, and it shows up correctly on the page and everything is fine.
I need to override some of the control's fields on one of the pages that derive from Site.Master.
// In OnLoad:
MyControlName control = (MyControlName) Page.Master.GetBaseMasterPage().FindControl("controlID"));
The issue is that MyControlName doesn't register as a valid Type on the child page. If I add a second instance of the control to the child page directly, the above works as needed, but if the control isn't placed directly on the page, and instead is only defined in the master page, the type is undefined. The control is not in a namespace, and is defined within the project, so I don't know why it is having such an issue location the appropriate type.
If I put a breakpoint in the OnLoad, the type listed for the control is ASP.my_control_name_ascx, but using that does not work either.
Why can't the child class reference the correct type? Can I fix this?
Thanks!
The control does not have global scope over the entire project. It will only be selectable as a type on pages where the control is registered. So you have to register the control on the child page:
<%@ Register src="WebUserControl.ascx" tagname="WebUserControl" tagprefix="uc1" %>
You will need to add a register tag like above to the top of your child aspx page.
The other option is you could create an interface for the control which exposes the properties or methods you want to access, and put the interface in app_code or some other globally accessible place, then have the control implement the interface, and cast the control to the interface.
The following code works for me:
DropDownList ddlLanguage = (DropDownList)Page.Master.FindControl("ddlLanguage");
I take it GetBaseMasterPage() is your own method? What happens if you try:
MyControlName control = (MyControlName)Page.Master.FindControl("controlId");
?
Not a direct answer to your question, but you might find the @MasterType
directive useful.
If you add a line like
<%@ MasterType TypeName="ClientName.SiteName.MasterPages.SiteMaster" %>
to the top of your ASPX page, you should be able to refer to the master page in code without having to cast it. This might make it easier for the code to find your control, perhaps?
You could end up with a line like:
// In Page.OnLoad:
MyControlName control = Page.Master.MyControl;
and then expose a new property in your master page that wraps the FindControl
call:
// In Site.master.cs
internal MyControlName MyControl
{
get { this.FindControl("controlID"); }
}
Hope this helps!
精彩评论