i have a web custom control
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="WebUserControl1.ascx.cs"
Inherits="WebApplication5.WebUserControl1" %>
<asp:DropDownList ID="ddlnew" AutoPostBack="true" runat="server"
onselectedindexchanged="ddlnew_SelectedIndexChanged">
<asp:ListItem Text="text1" />
<asp:ListItem Text="text1" />
<asp:ListItem Text="text2" />
<asp:ListItem Text="text1" />
<asp:ListItem Text="text2" />
<asp:ListItem Text="text2" />
</asp:DropDownList>
and on the Default.aspx page
<asp:Button Text="PostBack" ID="btnPost" runat="server"
onclick="btnPost_Click" />
and on the Default.aspx.cs
protected void btnPost_Click(object sender, EventArgs e)
{
WebUserControl1 uc = (WebUserControl1)Page.LoadControl("~/WebUserControl1.ascx");
PlaceHolder.Controls.Add(uc);
}
and when we select any item from dropdown it postback and the control hide from the page
so please help how it can be prevented from hide
thanks
Dynamically created controls must be recreated on every postback
, when you realise that each postback creates a new instance of the Page
class, and within this instance you must re-create all of the controls each and every time, this becomes more obvious.
Here is a good article on this
Another post on this that i answered
And another
To maintain state between the postbacks, you can use ViewState
or ControlState
MSDN Control State vs View State Example
protected void ddlnew_SelectedIndexChanged(object o, EventArgs e)
{
ViewState["ddlnew_value"]=ddlnew.selectdeitem;
}
than in page load pu this
If(IsPostBack)
{
if(ViewState["ddlnew_value"]!=null)
{
ddlnew.selecteditem=ViewState["ddlnew_value"];
}
}
this should work
In ASP.NET, dynamically loaded controls require a bit of attention because of their behavior across postbacks. You must Maintain Viewstate for Dynamic controls across the postback or check that on which control's is generating postback you will load the control or not..
Check these articles ( Specially MSDN reference ) :
An Extensive Examination of User Controls - MSDN
Loading UserControl Dynamically in UpdatePanel
Maintain Viewstate for Dynamic controls across the postback
1) You need to enable view state on the page.
2) Like others in this post mentioned you need to recreate the dynamically loaded user control.
Here's an example:
protected void Page_Load(object sender, EventArgs e)
{
Render();
}
Render Method:
private void Render()
{
var list = Helpers.Content.Lists.GetListByTitle();
if (list != null && list.Items.Count > 0)
{
this.divContainer.Controls.Clear();
var i = 1;
list.Items.ForEach(question =>
{
this.divContainer.Controls.Add(RenderQuestion(question, i));
i++;
});
}
}
Render Question Method:
private Control RenderQuestion(Entities.Modules.Item question, int count)
{
// Create question control
var q = (Custom.Widgets.ActionPlans.New.Question)LoadControl("~/Custom/Widgets/ActionPlans/New/Question.ascx");
// Render question
q.Render(question, count);
return q;
}
Hope this helps.