loading usercontrols dynamically - postback issue - c#

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";

Related

textbox does not accept a value in asp.net

This code a have written for an asp.net website, v2005
System.Web.UI.WebControls.TextBox txtEFName = new System.Web.UI.WebControls.TextBox();
phFname.Controls.Add(txtEFName);
placeHolder1.Controls.Add(TextBox1);
This code when executed, always shows the value of the textbox "" even if I enter some string.
Please help.
Dynamic controls need to be re-created each time the page loads. So you need to have that code execute during the Page_Init event. Note: You need to assign a unique ID for this control that stays the same each time the page loads.
Why all this?
Because the control is not contained in the markup (the .aspx file), you need to add it again every time the page loads. So how does it retain its value? The value will be stored in the ViewState, and as long as the control has the same ID it will be repopulated with the correct value.
To keep things running smoothly, let's put the code for adding the control in a separate function.
Private void AddMyControl()
{
System.Web.UI.WebControls.TextBox txtEFName = new System.Web.UI.WebControls.TextBox();
txtEFName.ID = something unique;
phFname.Controls.Add(txtEFName);
}
So we can call it from both the click handler and the Page_Init handler, but we only need to call it in the Page_Init if we have already clicked. So let's store that as a flag inside a Session variable (you can also store it in the ViewState if you like, but let's keep it that way for now). So our click handler will now look something like this:
void ButtonSomething_Click(Object Sender, EventArgs e)
{
AddMyControl();
Session["MyControlFlag"] == true;
}
Now we need our Page_Init handler:
Public void Page_Init(Object Sender, EventArgs e)
{
if(Session["MyControlFlag"]!=null && (bool)Session["MyControlFlag"])
AddMyControl();
}

User control not displayed after postback

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){}.

Add Event to Control added dynamic

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!

ASP.NET : How to store placeholder in viewstate?

I am trying to develop a page.
that has a button and a placeholeder.
on the click of the button a user control is added to the placeholder.
on each click of button that many user controls should be added to the placeholder.
i am trying to store placeholder in viewstate on preinit event but while retrieving placeholder from viewstate in load event viewstate remains null.
below is my code:
protected void PreInit(object sender, EventArgs e)
{
this.OnPreInit(e);
if (!Page.IsPostBack)
{
ViewState["c"] = PlaceHolder1;
}
else { PlaceHolder1 = (PlaceHolder)ViewState["c"]; }
}
protected void Page_Load(object sender, EventArgs e)
{
if(IsPostBack)
{ PlaceHolder1= (PlaceHolder)ViewState["c"]; }
}
public void addDepartmentBtn_Click(object sender, EventArgs e)
{
// User Control Code
c1 = LoadControl("~/AddDepartment.ascx");
PlaceHolder1.Controls.Add(c1);
}
If viewstate is not suitable in this scenarion then what is the alternative way to achieve this ?
You have to re-add controls to your place holder on each post back.
Your attempt to ViewState is barking up the wrong tree-- ViewState is for something entirely different and even if you wanted to, you can only store serializable things into ViewState.
If you are trying to add controls to the page dynamically, that must be done in Init on each postback. This means that you must use a data structure (something persisted in ViewState will do) as a list of dynamically-created controls- NOT the controls themselves, but a hash of strings to use as IDs is a common method.
Each time the user does something to add a control to the page, add a key to the list. In the Page Init, you must then read the list and use it to recreate and add the dynamic controls back to the page collection or they will not appear on the page.
This is not going to work. ASP.NET server controls are too complex a thing to be stored in a ViewState. What server controls do, by ASP.NET design, is store their data (state, property values, etc) in Page's ViewState.
What you can do is store in ViewState the number of AddDepartment user controls that have been created and added to the placeholder. This can be done in PreRender. Then on postback, you read this number from the ViewState and create and add to placeholder that many AddDepartment controls.

Change the master page when clicking a button in master

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

Categories