I have a home.aspx page, where i have two panel. In first panel I have dynamically bound a User Control (for displaying meiny at left side) and in second I have displayed pages.
I bound user control dynamically at page load like.
if (!IsPostBack)
{
UserControl uc = (UserControl)Page.LoadControl("~/settings/Links/Navigation.ascx");
Accordion1.Controls.Add(uc);
}
when page first time loaded my usercontrol is bind and my menus are displayed, but when I clicked on any menu item it hides(user control),
Please help me, thanks in advance!
Put this line of code on Page_Init event of Page life cycle.
UserControl uc = (UserControl)Page.LoadControl("~/settings/Links/Navigation.ascx");
Accordion1.Controls.Add(uc);
Proper way:
protected void Page_Init(object sender, EventArgs e)
{
//MyControl is the Custom User Control with a code behind file
MyControl myControl = (MyControl)Page.LoadControl("~/MyControl.ascx");
//UserControlHolder is a place holder on the aspx page where I want to load the
//user control to.
UserControlHolder.Controls.Add(myControl);
}
If you use if (!IsPostBack) then after postback it will not be added to the page. At the first time you will be able to see the control on the page.
Reference:
ASP.NET Custom user control to add dynamically
How to: Create Instances of ASP.NET User Controls Programmatically
It's a dynamic control which must be recreated and readded to the page on every postback.
So this will work:
//if (!IsPostBack)
//{
UserControl uc = (UserControl)Page.LoadControl("~/settings/Links/Navigation.ascx");
Accordion1.Controls.Add(uc);
//}
For Dynamic control there is no need for !IsPostBack Property of page, Remove this property and use
UserControl uc = (UserControl)Page.LoadControl("~/settings/Links/Navigation.ascx");
Accordion1.Controls.Add(uc);
It must be loaded on each postback. keep the user control loading code outside if(!IsPostBack){}.
Related
I have a user control with a DropDownList with AutoPostBack = true, also I have an aspx page to display this control.
I re-create user control in OnInit method of the page
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
var list = (List<Control>)Session[Controls];
if (list != null)
{
foreach (var control in list)
{
var uc = (Control)LoadControl(ControlPath);
uc.SetDropDownState(control.state);
PlaceHolderQuestion.Controls.Add(uc);
}
}
}
So while re-creating I am restoring DropDown selection, it works for the first time, but when I change selection again, OnSelectedIndexChanged event does not fire and it is obvious because I first restore DropDown selection in OnInit and so no OnSelectedIndexChanged event, cause nothing was changed, can you suggest some workaround?
UPDATE
var uc = (Control)LoadControl(ControlPath);
is required to be keep user controls events
After a deep research, I figured out that the issue was in the SelectedIndexChanged event logic.
I am using "Indirect Subscription" approach to handle it within my Page logic,
for more info please take a look
Indirect Subscription Approach
Originally I was reloading controls inside the handler but it was not required since I am doing it in the Page_Load method as well, so all I need to do is to update control inside my PlaceHolder controls list.
I hope it is clear, if not, please ask, and I will provide more description.
I'm using asp.net and c# for webForm. I'm generating a dropDownList dynamically, but I can't execute an event for this control. Below some code:
DropDownList nuevoCmb = new DropDownList();
nuevoCmb.ID = "ddl" + num;
nuevoCmb.Items.Add("---Seleccione el Plazo---");
nuevoCmb.Items.Add("Corto Plazo");
nuevoCmb.SelectedIndex = 0;
nuevoCmb.AutoPostBack = true;
nuevoCmb.SelectedIndexChanged += new EventHandler(nuevoCmb_OnSelectedIndexChanged);
MainPanel.Controls.Add(nuevoCmb);
protected void nuevoCmb_OnSelectedIndexChanged(object sender, EventArgs e)
{
string temp = "";
}
You need to add the code that creates the control to every page request, including postbacks. If the control causes a postback and the code that recreates the control is not called, your event handler will not fire. .NET will eventually call your event handler once a control with the same ID is added during the page load.
You should add dynamically added controls in or before the page Init event. It also works if you add during page Load event. After the Load event, your custom control events bubble up and fire. So if you're adding controls dynamically, they have to be added on each post back, being loaded before the page Load event ends, at the latest.
I found an answer in the follow page: Creating Dynamic DropDownList Controls in ASP.Net
This example is fully functional, but only an asp html page, is not working using master page. Any suggestion!
I am having three master pages like Master-Green, Master-Bule, Master-Red. In each master page having three buttons named as green, blue and red.
Now my default master is green,
It's assigned a page Default.aspx. At this time three button also display on the top.
How to make so clicking "blue" button means the Master-Blue shold be master page for the current page?
In the Master Page use input type submit button
<input type="submit" name="btnGreen" value="Green" />
<input type="submit" name="btnBlue" value="Blue" />
2.Then from the code behind you can check the name of the button clicked, in the Request object in the Page_PreInit event
public partial class Default : System.Web.UI.Page
{
protected void Page_PreInit(object sender, EventArgs e)
{
if (Request["btnGreen"] != null)
{
Page.MasterPageFile = "/Green.Master";
}
else if (Request["btnBlue"] != null)
{
Page.MasterPageFile = "/Blue.Master";
}
}
}
Dealing with dynamic master pages might look easy at first sight but it's a little tricky.
Consider the following:
A MasterPage is actually considered as a child control of the page, therefore, its life-cycle is like any other control on the page
In order to change the MasterPage at runetime, it has to be done in the PreInit event of the page (remember that controls do not have this event, therefore the MasterPage does not have it either)
As a reminder, the PreInit, Init, and Load events of the page life cycle work as follows: The page's PreInit event is fired, followed by all the Init events of the page's child controls (including the MasterPage), when all child Init events have been raised, the page's Init event is fired and finally the page's InitComplete event is fired indicating all Init events have been processed. The Load events work the other way around, the page's Load event is fired first, followed by all the child control's Load events and at the end, the page's LoadComplete event.
The Post back event that caused the page's post back is raised after all child control's Load events have been fired but before the page's LoadComplete event
In the PreInit event you do not have access to the page ViewState
Source: http://msdn.microsoft.com/en-us/library/ms178472.aspx
Quick Look:
So why is this so important?
In your example you have three buttons, each time a button is pressed, you need to change the MasterPage, but the MasterPage must be changed in the PreInit event of the page, but your button handler is processed after that, so the tricky part is to call Server.Transfer to re-process the page.
Note. Since you are allowing the user to personalize the MasterPage, you need a way store his preferences, usually you would use a cookie, or a database. In this sample I am going to use the Session object for simplicity but you can change it to fit your needs.
So this would look something like:
Master page code behind
protected void blueMasterPage_Click(object sender, EventArgs e)
{
this.Session["master"] = "BlueMasterPage";
this.Server.Transfer(this.Request.RawUrl);
}
In the page code behind
protected void Page_PreInit(object sender, EventArgs e)
{
if (this.Session["master"] != null)
{
this.MasterPageFile = string.Format("~/{0}.master", (string)this.Session["master"]);
}
}
Note: If you do not use Server.Transfer you won't see the changes to the page's MasterPage until the next time you do a post to the page
So this was tricky, and in my opinion, we should be able to do the same easier, one more time the ASP.Net page's life cycle doesn't help at all.
You can always follow the #AndreCalil suggestion about using just one master page and different CSS layouts for your site
Edit 1
One thing that I forgot to mention, is that you need to set the master page in all your pages consuming the dynamic MasterPage, so the best way to do it, is create a base page and inherit from it, and in the base page write the code in the PreInit event to set the MasterPage
Im trying to load a usercontrol dynamically on a aspx page however it works but i get postback issues?? I have a image button on usercontrol which I want to show a image however when i do click on button the page refreshes and does not show image?. I have a placeholder on aspx page and backend code i have this :
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Control uc = Page.LoadControl("~/UserControls/Mycontrol.ascx");
placeholder1.Controls.Add(uc);
}
}
Do i need to do something in page_preinit or page_init ??
You should always reload the user control on the Page_init on each post back.
Dynamic controls added to the page must be added on every postback, not just the first one. Remove the !IsPostBack condition. Secondly, they have to be added during init or preinit, because that way, viewstate will be captured and restored properly (ASP.NET restores viewstate between init and load events).
Give the control an ID and also load the control in Page_init
uc.ID = "your id";
I have a masterpage and inside that masterage is a user control that has a toolbar with a save button. I then have an aspx page that inherits form t he master page. In that page I have and updatepanel. Is it possible to set the post back trigger to the Save button inside the usercontrol?
You should be able to use Master.FindControl("MySaveButton") from within the content page, and attach it to the scriptmanager's trigger list:
this.MyScriptManager.RegisterAsynchPostBackControl(Master.FindControl("MySaveButton"))
Unless I'm not understanding the question correctly.
Check the fourth post down (marked as answer) here, it ought to help.
In short, create an PostBackTrigger instance, set fields appropriately and then add to the UpdatePanel's Triggers collection.
For example (from linked site):
//Creates a new async trigger
AsyncPostBackTrigger trigger = new AsyncPostBackTrigger();
//Sets the control that will trigger a post-back on the UpdatePanel
trigger.ControlID = "btnCommit";
//Sets the event name of the control
trigger.EventName = "Click";
//Adds the trigger to the UpdatePanels' triggers collection
pnlMain.Triggers.Add(trigger);
I went with a different approach of find my controls. I used this method. I have used this in the past and not sure why I didn't think about it earlier. In my user control I expose controls as properties. In my master page I created a property that allows me to get the user control instance. In my page I can call this: Master.UserControlName.PropertyInControl
So, if I expose a button or control in the user control, I should be able to add that to the trigger collection.