Acess a control of a user control in a content page of a master page - asp.net

I have user control (ascx) in a Master Page.
Then I have a content page (aspx) that uses that Master Page.
Now, in the content page, I want to access a hiddenfield control that is placed in the user control.
How do I do that?
I tried the following but it returns null.
Master.FindControl("MyHiddenField")
Master.FindControl("MyUserControl1_MyHiddenField")
Thanks

In your content page (.aspx) place this code. It will make the Master Page strongly typed for the content page.
<%-- The Page directive goes here --%>
<%# MasterType TypeName="MyMasterClassName" %>
<%-- Rest of your code below.. --%>
In the Master Page code behind, place this code
public UserControlTypeName MyUserControl1
{
get {return myUserControl1; }
set {}
}
This makes the User Control instance public. You'll need to rename the ID of the user control to myUserControl1.
Then in your UserControlTypeName (or whatever the name of your class is for your User Control) you can make the inner controls accessible in the same manner we did on the master page.
public HiddenField
{
get {return myHiddenField;}
set {}
}
Obviously, rename the ID for MyHiddenField to myHiddenField to avoid a conflict.
Finally, this allows your content to access the controls within the user control that are on the master page through strong typing.
public void Page_Load(object sender, EventArgs e)
{
Master.MyUserControl1.MyHiddenField.Value="Hello, world!";
}
For further reference, see Working with ASP.NET Master Pages programmatically on MSDN.
If Microsoft Is Listening...
If for some reason a Microsoft ASP.NET developer is reading this answer, please consider doing something like this:
<asp:Button runat="server" scope="public" id="MyButton1 />
That would make it much easier than having to create wrapper properties to make inner controls publicly accessible.

Related

Accessing text boxes in a web control on a master page

I need to access multiple textboxes on a master page. The textboxes are declared in a separate web control and it won't let me call the names of the textboxes so I can populate them with data. I have multiple textboxes like I said, but for example, when I try to write to txtName it will not let me even though when I click on the Design View it says it is there.
Can anybody help me out?
Expose the text boxes inside the web control as properties.
In webcontrol.ascx
<asp:TextBox runat="server" id="txtName" />
In webcontrol.ascx.cs
public virtual TextBox TxtName { get {return txtName;} //note capitalization
Then do the same thing in the master page to expose the web control.
In masterpage.master
<uc1:MyWebControl runat="server" id="MyWebControl1" />
In mastermage.master.cs
public virtual MyWebControl myWebControl{get {return myWebControl1;}}
Then make your master page strongly typed from the content page by adding a MasterType directive.
In default.aspx
<%# MasterType TypeName="MyMasterPageClass" />
Then you can access it from your content page code behind. In default.aspx.cs
Master.myWebControl.TxtName.Text="Hello, world!";
The reason it's necessary to do this is that controls declared on .aspx, .ascx, and .master pages are protected instead of public and there's no way (as of right now) to change them that I'm aware of. So we can use properties to expose these controls as public.

Registering a user control always postback hen the form loaded

Hi all I have created a user control and registered it in web.config with some extension and calling it on the page where ever required. When I use that when ever the page get loaded the user control also getting loaded, i mean the post back event of the user control or the page load event occurs as per the operations made in web page.
Is there any way to avoid this in such a way that only the user control page load should enable or load when ever some operations performed on that control when loaded.
For example I have created a user control and registered on my form, this will get loaded on button click of the form, I would like to make the post back of user control only when user click on the button of the web form but not on every operations performed
Edit as per jadarnel27 answer
<%# Register Src="~/UserControl1.ascx" TagName="TimeoutControl" TagPrefix="uc1" %>
<asp:Panel ID="yourPanelControl" runat="server" Height="200px" Width="300px">
</asp:Panel>
<dx:ASPxButton ID="btn" Text="user" OnClick="btn_Click" runat="server">
</dx:ASPxButton>
protected void btn_Click(object sender, EventArgs e)
{
TimeoutControl tc = new TimeoutControl();
yourPanelControl.Controls.Add(tc);
}
But I am unable to see the postback event fires on page load of user control as per ur code
When the ASP.NET Page loads, it recursively calls the Load function of all the controls in the Page.Controls collection (see the "Life Cycle events" section of this MSDN article on The ASP.NET Page Life Cylce, specifically the "Load" event). Including the UserControl in the markup of your page will cause it to be part of this collection, so the load event will fire whenever the Page loads.
If you want to avoid this, you need to add the UserControl to the Page dynamically in response to the Button's click event. You could, for instance, include some kind of Panel in your Page, then add the UserControl to that Panel when you click the Button.
Something like this:
protected void yourButton_Click(Object sender, EventArgs e)
{
// Create your UserControl
yourUserControl uc = new yourUserControl();
// Add it to the Panel you included in your markup
yourPanelControl.Controls.Add(uc);
}
The markup for a Panel would be something like this:
<asp:Panel id="yourPanelControl" runat="server" Height="200px" Width="300px">
</asp:Panel>

Floodlight tag in asp.net master page

I am planning to implement floodlight tag in my website. I know I need to place the floodlight tags after body tag. But they way my website is designed that all the aspx pages use one single master page. Since the master page is going to contain the body tag. How to add floodlight tags for each page?
Thanks
You could put a Literal control after your body tag in the master page and set this in your aspx code behind i.e.,
In you master page...
...
</body>
<asp:Literal id="ltrFloodlightTag" runat="server"></asp:Literal>
Then in an aspx.cs page where the masterpage is used...
protected void Page_Load(object sender, EventArgs e)
{
....
Literal ltrFloodlightTag = (Literal)Master.FindControl("ltrFloodlightTag");
ltrFloodlightTag.Text = "<img src='http://flodlightstuff/info.aspx?this=123&that=321' width='1px' height='1px' />";
}
Similarly, you could just use an img in the masterpage and simply set the src attribute from the aspx (if there is going to be a floodlight on each page this might make more sense).
I think this is what you might be getting at and I've actually got the meaning of floodlight tags correct!

How to find user control of an ASP.NET page inside of event of another user control on that ASP.NET page EDIT: different content placeholders?

I have a ASP.NET page with 2 user controls registered. The first one has only one button in it. The second one is simple text and hidden on default. What I want is to make the second one visible when the button in the first one is clicked (that is on button click event).
ASP.NET page:
<%# Page Title="" Language="C#" CodeFile="test.aspx.cs" Inherits="test" %>
<%# Register Src="~/UC_button.ascx" TagName="button" TagPrefix="UC" %>
<%# Register Src="~/UC_text.ascx" TagName="text" TagPrefix="UC" %>
<asp:Content ID="Content1" ContentPlaceHolderID="MyTestContent" Runat="Server">
<UC:button ID="showbutton1" runat="server" />
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MyTestContent2" Runat="Server">
<UC:text runat="server" Visible="false" ID="text1" />
</asp:Content>
UC_Button.ascx.cs:
protected void button1_Click(object sender, EventArgs e)
{
Button btnSender = (Button)sender;
Page parentPage = btnSender.Page;
UserControl UC_text = (UserControl)parentPage.FindControl("text1");
UC_text.Visible = true;
}
What am I doing wrong? I get well known Object reference not set to an instance of an object. error on that last line of the code.
EDIT:
One thing I forgot to mention when first posting this. User controls are in different <asp:Content></asp:Content> controls (I edited upper example). If I put them in the same placeholder code works just fine. If I put them in the separate content placeholders I can't find them in any way with findcontrol. Why is that and how can I find them?
please check below:
UserControl UC_text = (UserControl)this.NamingContainer.FindControl("text1");
The FindControl method does not do a deep search for controls. It looks directly in the location you specify for the control you're requesting.
In your case, what you'll need to do is something like:
UserControl UC_text = (UserControl)Content1.FindControl("text1");
You can also see my question here: IEnumerable and Recursion using yield return that demonstrates a method of finding deep controls by type.
Ok I found solution until better one comes my way. The problem is, as Jamie Dixon pointed out (thank you Jamie):
The FindControl method does not do a deep search for controls. It looks directly in the location you specify for the control you're requesting.
So because I have user controls in different contentplaceholders I must first find targeted placeholder (where the user control reside) and then I can search for user control inside it:
protected void Dodaj_Feed_Panel_Click(object sender, EventArgs e)
{
ContentPlaceHolder MySecondContent = (ContentPlaceHolder)this.Parent.Parent.FindControl("MyTestContent2");
UserControl UC_text = (UserControl)MySecondContent.FindControl("text1");
UC_text.Visible = true;
}
what really annoys and confuses me is the this.Parent.Parent part because I know it's not the best solution (in case I change the hierarchy a bit this code will break). What this part of code actually does is that it goes two levels up in page hierarchy (that is page where both user controls are). I don't know what the difference with this.Page is because for me it means the same but is not working for me.
Long term solution would be something like server side "jQuery-like selectors" (it can found elements no matter where they are in hierarchy). Anyone has a better solution?
use the id of user control,then put the controls (e.g Textbox) inside panel then
try this code from the main page
example:
TextBox txt = (TextBox)showbutton1.FindControl("Textbox1");
for updating with udpatepanel:
TextBox txt = (TextBox)showbutton1.FindControl("Textbox1");
txt.Text="Hello World!";
((UpdatePanel)showbutton1.FindControl("UpdatePanel1")).Update();

Add packaged javascript to page from ASP.NET server control?

Is it possible to create an ASP.NET server control that packages some javascript that will be emitted to the aspx page at design-time rather than run time? I am trying to create a control that will have "default" javascript. I can add jvascript using RegisterClientScriptBlock, but then a web developer can't modifiy the javascript - it is unavailable a design-time in this scenario. Is there a way to change the ToolBox properties so that when a web developer drops the control onto the page, the javascript is added in a separate script tag as well?
When I need to do this I make a property on the control that will inject the tags, and then the web dev makes a asp:literal tag that has visibility none and viewstate disabled, that has all the JS they need.
then in the page's code behind they inject the literal's text into the server controls properties.
<asp:Literal ID="Literal_HtmlHeader" runat="server" Visible="false" EnableViewState="false">
<script></script>
<style></style>
</asp:Literal>
there are probably better ways... but this is simple and effective for me.
protected void Page_Load(object sender, EventArgs e)
{
if (!String.IsNullOrEmpty(this.Literal_HtmlHeader.Text.Trim()))
{
//inject css and js into header.
Page.Header.Controls.Add(new LiteralControl(this.Literal_HtmlHeader.Text));
// or add to your control cause it knows how to add the tags so there is no duplication.
ServerControl c = new ServerControl();
c.HtmlHeaderCode = this.Literal_HtmlHeader.Text.Trim();
}
}

Resources