Button created from code behind disappeared after click [duplicate] - c#

Actually, I am Creating 1 TextBox on Pageload and adding that TextBox to Panel.
Now, I have a LinkButton like Add Another.
I am entering Text in that TextBox and if needed I need to Create New TextBox,by clicking Add Another LinkButton.
Actually, I am able to get the count and recreate the TextBoxes.
But,the Problem is that, My Entered text in the Previously Generated Textboxes is Missing.
Can Anyone,Suggest me a solution for this?
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (!IsPostBack)
{
for (int i = 0; i < 5; i++)
{
TableRow row = new TableRow();
for (int j = 0; j < 5; j++)
{
TableCell cell = new TableCell();
TextBox tb = new TextBox();
tb.ID = "TextBoxRow_" + i + "Col_" + j;
cell.Controls.Add(tb);
row.Cells.Add(cell);
}
Table1.Rows.Add(row);
}
}
}
catch (Exception ex)
{
throw;
}
}
This is a Sample Code, the same code is written in Button_Click Also
protected void ASPxButton1_Click(object sender, EventArgs e)
{
int k = Table1.Controls.Count;
}
I am getting a Count=0 on Button_Click.

All you need to do is to re-instantiate / reinitialize dynamic controls before or within page load event each and every time during postback and add this control to page / forms / placeholders. Then, the posted data will automatically be assigned to the control by calling the LoadPostData method by the parent control.
check the article and how to write code for dynamic control -
How to maintain dynamic control events, data during postback in asp.net

When using dynamic controls, you must remember that they will exist only until the next postback.ASP.NET will not re-create a dynamically added control. If you need to re-create a control multiple times, you should perform the control creation in the PageLoad event handler ( As currently you are just creating only for first time the TextBox using Condition: !IsPostabck ). This has the additional benefit of allowing you to use view state with your dynamic control. Even though view state is normally restored before the Page.Load event, if you create a control in the handler for the PageLoad event, ASP.NET will apply any view state information that it has after the PageLoad event handler ends.
So, Remove the Condition: !IsPostback, So that each time the page Loads, The TextBox control is also created. You will also see the State of Text box saved after PageLoad handler completes. [ Obviously you have not disabled ViewState!!! ]
Example:
protected void Page_Load(object sender, EventArgs e)
{
TextBox txtBox = new TextBox();
// Assign some text and an ID so you can retrieve it later.
txtBox.ID = "newButton";
PlaceHolder1.Controls.Add(txtBox);
}
Now after running it, type anything in text box and see what happens when you click any button that causes postback. The Text Box still has maintained its State!!!

The dynamically generated control do not maintain state. You have to maintain it at your own. You can use some hidden field to keep the state of controls, which will be used on server side to extract the state. Asp.net uses hidden field to maintain the state between requests, you can see __VIEWSTATE in the source.
In ASP.NET pages, the view state represents the state of the page when
it was last processed on the server. It's used to build a call context
and retain values across two successive requests for the same page. By
default, the state is persisted on the client using a hidden field
added to the page and is restored on the server before the page
request is processed. The view state travels back and forth with the
page itself, but does not represent or contain any information that's
relevant to client-side page display, Reference.

Just remove this line
if (!IsPostBack)

This is My final answer after working a lot with Dynamic Controls
.aspx
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<div style="text-align: center">
<div style="background-color: Aqua; width: 250px;">
<br />
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:PlaceHolder runat="server" ID="myPlaceHolder"></asp:PlaceHolder>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnAddTextBox" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
<br />
</div>
<br />
<asp:Button ID="btnAddTextBox" runat="server" Text="Add TextBox" OnClick="btnAddTextBox_Click" />
<br /><br />
<asp:UpdatePanel ID="UpdatePanel2" runat="server">
<ContentTemplate>
<asp:Button runat="server" ID="MyButton" Text="Get Values." OnClick="MyButton_Click" />
<br /><br />
<asp:Label runat="server" ID="MyLabel"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
.aspx.cs
static int myCount = 0;
private TextBox[] dynamicTextBoxes;
protected void Page_PreInit(object sender, EventArgs e)
{
Control myControl = GetPostBackControl(this.Page);
if ((myControl != null))
{
if ((myControl.ClientID.ToString() == "btnAddTextBox"))
{
myCount = myCount + 1;
}
}
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
dynamicTextBoxes = new TextBox[myCount];
int i;
for (i = 0; i < myCount; i += 1)
{
TextBox textBox = new TextBox();
textBox.ID = "myTextBox" + i.ToString();
myPlaceHolder.Controls.Add(textBox);
dynamicTextBoxes[i] = textBox;
LiteralControl literalBreak = new LiteralControl("<br />");
myPlaceHolder.Controls.Add(literalBreak);
}
}
protected void btnAddTextBox_Click(object sender, EventArgs e)
{
// Handled in preInit due to event sequencing.
}
protected void MyButton_Click(object sender, EventArgs e)
{
MyLabel.Text = "";
foreach (TextBox tb in dynamicTextBoxes)
{
MyLabel.Text += tb.Text + " :: ";
}
}
public static Control GetPostBackControl(Page thePage)
{
Control myControl = null;
string ctrlName = thePage.Request.Params.Get("__EVENTTARGET");
if (((ctrlName != null) & (ctrlName != string.Empty)))
{
myControl = thePage.FindControl(ctrlName);
}
else
{
foreach (string Item in thePage.Request.Form)
{
Control c = thePage.FindControl(Item);
if (((c) is System.Web.UI.WebControls.Button))
{
myControl = c;
}
}
}
return myControl;
}

When you are working with dynamic controls they will not able to maintain its state during postback and their data lost Cause they dont have any viewstate to maintain their data.
You only need to maintain the created controls data into ViewState
dynamically and loads the data into page at the time of postback and you
done.
public Dictionary<Guid, string> UcList
{
get { return ViewState["MyUcIds"] != null ? (Dictionary<Guid, string>)ViewState["MyUcIds"] : new Dictionary<Guid, string>(); }
set { ViewState["MyUcIds"] = value; }
}
public void InitializeUC()
{
int index = 1;
foreach (var item in UcList)
{
var myUc = (UserControls_uc_MyUserControl)LoadControl("~/UserControls/uc_MyUserControl.ascx");
myUc.ID = item.Value;
pnlMyUC.Controls.AddAt(index, myUc);
index++;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadControl();
else
InitializeUC();
}

Actually, I have used Javascript for accomplishing my task.
and it goes like this :
<form id="form1" runat="server" enctype="multipart/form-data" method="post">
<span style="font-family: Arial">Click to add files</span>
<input id="Button1" type="button" value="add" onclick="AddFileUpload()" />
<br />
<br />
<div id="FileUploadContainer">
<!--FileUpload Controls will be added here -->
</div>
<asp:HiddenField ID="HdFirst1" runat="server" Value="" />
<br />
<asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" />
</form>
Script :
<script type="text/javascript">
var counter = 0;
function AddFileUpload() {
var div = document.createElement('DIV');
div.innerHTML = '<input id="file' + counter + '"name = "file' + counter + '"type="text"/><input id="file' + counter + '" name = "file' + counter + '" type="file" /><input id="Button' + counter + '" type="button" value="Remove" onclick = "RemoveFileUpload(this)" />';
document.getElementById("FileUploadContainer").appendChild(div);
counter++;
}
function RemoveFileUpload(div) {
document.getElementById("FileUploadContainer").removeChild(div.parentNode);
}
function mydetails(div) {
var info;
for (var i = 0; i < counter; i++) {
var dd = document.getElementById('file' + i).value;
info = info + "~" + dd;
}
document.getElementById('<%= HdFirst1.ClientID %>').value = info;
}
</script>
and In the Upload_Click Button :
for (int i = 0; i < Request.Files.Count; i++)
{
string strname = HdFirst1.Value;
string[] txtval = strname.Split('~');
HttpPostedFile PostedFile = Request.Files[i];
if (PostedFile.ContentLength > 0)
{
string FileName = System.IO.Path.GetFileName(PostedFile.FileName);
// string textname=
//PostedFile.SaveAs(Server.MapPath("Files\\") + FileName);
}
}

Related

add multiple innerhtml in asp.net

my x.aspx file :-
<form id ="Content3ret" runat="server">
</form>
<asp:Button ID="Button1" runat="server" OnClick ="Button1_Click"/>
my x.aspx.cs file :-
protected void Button1_Click(object sender, EventArgs e)
{
var x = Guid.NewGuid().ToString();
Content3ret.innerhtml = "<table id = '"+x+"'> <tr> <td><input type='radio' name='radiotest' checked='checked'/></td> </tr> </table>";
}
what I am trying to do is :-
when I click button each and every time there should be new radio button added with other .
like 3 button click I need 3 radio button .
but with this code when I click only one radio button creating .
like 3 click only one radio button with new id.
can anyone help me ?
When you add data on Content3ret.innerhtml and render them on the pages, this data are lost / gone / stay on page and never come back on post back - because this inner html is not post back with the second click on button.
So you have to render them on page, and at the same time saved it somewhere - preferable on viewstate because of asp.net
so the page will be like
<form id="form1" runat="server">
<div runat="server" id="divPlaceOnme"></div>
<asp:Button ID="Button1" runat="server" Text="ok" OnClick ="Button1_Click"/>
</form>
and on code behind we have
const string InnerHtmlKeeper_name = "InnerHtmlKeeper_cnst";
string InnerHtmlKeeper
{
get
{
var RetMe = ViewState[InnerHtmlKeeper_name] as string;
if (string.IsNullOrEmpty(RetMe))
return string.Empty;
else
return RetMe;
}
set
{
ViewState[InnerHtmlKeeper_name] = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
var x = Guid.NewGuid().ToString();
// we keep the new with the previous data on this ViewState
InnerHtmlKeeper += "<table id = '" + x + "'> <tr> <td><input type='radio' name='radiotest' checked='checked'/></td> </tr> </table>";
// we add the final render on the div on page
divPlaceOnme.InnerHtml = InnerHtmlKeeper;
}
Last words.
Your approaches have many issues - and your code not working as it is. The button must be on the form, and you have to render inside some other div.
The point here is to show you have to save some actions on viewstate - beside that for a good solution on your problem you must use some javascript to render the radio without post back.

How can I get all textbox from a placeholder? asp.net c# webform?

I have a asp:placeholder on my html and I'm accessing to it to add textboxes and labels for questions and answers.
The "form" is created correctly I got all the labels with the questions and a textbox for each answer, however when I try after the button click runatserver the Placeholder1 is always empty.
I have tried a lof of things to get the textbox values to insert on a database without luck.
Below my code.
HTML code for the form inside a webform:
/* form for the buttons and title*/
<form id="form2" runat="server">
<div align="center">
</div>
<div>
<div align="center" class="form-group">
<h4>
<asp:label runat="server" id="title"></asp:label>
</h4>
<br />
<br />
<div align="center">
place holder for the questions&answers
<asp:placeholder id="Placeholder1" runat="server">
</asp:placeholder>
</div>
</div>
</div>
<br />
<br />
C# code to get how many questions and then add a textbox for each answer, using the cicle with a counter to add a id+counter
/* c# a counter is made to increment a number to the id*/
Adding controls to the PlaceHolder1
/* add controls: */
add labels inside the counter for all number of rows of the sqlresult*/
Labels
Label quest= new Label();
quest.ID = "quest" + counter;
quest.Attributes.Remove("class");
quest.Attributes.Add("class", "exampleFormControlInput1");
quest.text = "sql query";
Textbox
/add textbox on the cicle/
TextBox answer = new TextBox();
answer .ID = "answer " + counter;
answer .Attributes.Remove("class");
answer .Attributes.Add("class", "form-control");
PlaceHolder1.Controls.Add(quest);
PlaceHolder1.Controls.Add(new LiteralControl("<br>"));
PlaceHolder1.Controls.Add(answer);
PlaceHolder1.Controls.Add(new LiteralControl("<br>"));
Check how many controls are inside of the PlaceHolder1
Trying to check how many controls in the PlaceHolder1
count = PlaceHolder1.Controls.Count;
always 0
You probably are not recreating the Controls on PostBack. See this working example.
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack == false)
{
//do not create controls here
}
for (int count = 0; count < 5; count++)
{
TextBox answer = new TextBox();
answer.ID = "answer " + count;
PlaceHolder1.Controls.Add(answer);
}
}
And then on PostBack
protected void Button1_Click(object sender, EventArgs e)
{
int count = PlaceHolder1.Controls.Count;
for (int i = 0; i < count; i++)
{
TextBox answer = PlaceHolder1.FindControl("answer " + i) as TextBox;
Label1.Text += answer.Text + "<br>";
}
}

Modal Panel Doesn’t Appear When Called by Button Inside a Grid View’s Cell

I've struggled a lot with how to show a modal panel on click on a button inside a grid view.
To context: I have a data row with a string field that can contain a simple text or a base 64 encoded image, so I'm using a custom template to define when to show the raw content or a button "View Image". This image will be opened on a modal panel that should rise up on button click.
This is the Panel I've created as a control (ascx):
<asp:Panel ID="pnlModalOverlay" runat="server" Visible="true" CssClass="Overlay">
<asp:Panel ID="pnlModalMainContent" runat="server" Visible="true" CssClass="ModalWindow">
<div class="WindowTitle">
<asp:Label ID="lbTitle" runat="server" />
</div>
<div class="WindowBody">
<asp:Panel ID="pnlContent" runat="server" Visible="true">
<asp:Image ID="imgContent" runat="server" CssClass="ImageView" />
</asp:Panel>
<div class="Button">
<asp:Button ID="btnOk" runat="server" class="btn btn-default " Text="Close" OnClientClick="loadingPanel.Show();" />
</div>
</div>
</asp:Panel>
</asp:Panel>
And this is the page and ASPxGridView where I wanna use it:
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional" ChildrenAsTriggers="true">
<ContentTemplate>
<div style="margin-top: 12px;">
<asp:Button type="button" ID="btnShowImage" AutoPostBack="true" class="btn btn-default navbar-right" Text="Show Image"
runat="server" Style="margin-left: 5px;" OnClientClick="loadingGridPanel.Show();" />
</div>
<!-- Some data filter controls -->
<MyWorkspace:AlertModal ID="alertModal" runat="server" Visible="false" />
<MyWorkspace:ImageModal ID="imageModal" runat="server" Visible="false" />
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="mainGrid" />
</Triggers>
</asp:UpdatePanel>
<MyWorkspace:GridViewWrapper ID="mainGrid" runat="server" Visible="true" />
Codebihind:
public partial class MyPage : System.Web.UI.Page
{
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
btnShowImage.Click += new EventHandler(ShowImage); // This call works fine
}
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (!IsPostBack)
{
mainGrid.CanEditItems = true;
mainGrid.CustomTemplates.Add(new CustomColumnTemplate { columnName = "Id", template = new LinkColumn(CreateParentLink, "Go to parent") });
mainGrid.CustomTemplates.Add(new CustomColumnTemplate { columnName = "Value", template = new ButtonColumn(ShowImage, "View Image") }); // This one doesn't works
}
}
catch (Exception ex)
{
modalAlerta.Show("Page_Load", ex.Message, false, false, "");
}
}
void ShowImage()
{
modalImagem.Show(); // Set Modal's Visible property to True
// UpdatePanel1.Update(); <-- Tryin' force it to work with no success
}
}
The ButtonColumn template creation:
public class ButtonColumn : System.Web.UI.ITemplate
{
private Action action;
private string controlId;
private string tooltip;
public ButtonColumn(Action onClick, string toolTip)
{
this.action = onClick;
this.controlId= "btnShowImage";
this.tooltip = toolTip;
}
public void InstantiateIn(System.Web.UI.Control container)
{
GridViewDataItemTemplateContainer gridContainer = (GridViewDataItemTemplateContainer)container;
if (System.Text.RegularExpressions.Regex.IsMatch(gridContainer.Text, "^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$"))
{
ImageButton button = new ImageButton();
button.ID = idControle;
button.ImageUrl = "/Images/html5_badge_64.png";
button.Width = 20;
button.Height = 20;
button.ToolTip = tooltip;
button.Click += (s, a) =>
{
if (onClick != null)
onClick();
};
container.Controls.Add(button);
}
else
{
Label label = new Label()
{
Text = gridContainer.Text,
ToolTip = tooltip
};
container.Controls.Add(label);
}
}
}
The method's call at the click of btnShowImage button works fine. But when I do the same call by one ImageButton (or button) inside the gridview it doesn't work. Both calls reach the ShowImage method.
Any help would be appreciated. Thank you all.
EDIT 1:
The GridView is encapsulated in GridViewWrapper (there I build the columns dynamically using a combination of class's properties gotten by reflection and stored metadata), this class have too much code to share here and I do not think it's the reason. Also, I've executed in debug mode and passed thru it step by step every relevant method inside this one.
The column add method:
CustomColumnTemplate customTemplate = CustomTemplates.FirstOrDefault(f => f.columnName == metadata.ColumnIdName);
gridView.Columns.Add(new GridViewDataColumn()
{
FieldName = metadata.ColumnIdName,
VisibleIndex = GetVisibleIndexByColumnIdName(metadata.ColumnIdName),
Caption = metadata.Caption,
Width = new Unit(DefaultColumnWidth, UnitType.Pixel),
DataItemTemplate = customTemplate == null ? null : customTemplate.template
});
I've made sure the ShowImage method is being hitten, but it behaves like the UpdatePanel1 isn't have been updated
The ASPxGridView stores information about columns in ViewState, but does not save information about column templates. This is made on purpose since templates can be very complex and their serialization makes ViewState very huge.
So, if you create columns with templates at runtime, disable ViewState:
ASPxGridView.EnableViewState="false"
and create columns on every callback:
//if (!IsPostBack)
//{
mainGrid.CanEditItems = true;
mainGrid.CustomTemplates.Add(new CustomColumnTemplate { columnName = "Id", template = new LinkColumn(CreateParentLink, "Go to parent") });
mainGrid.CustomTemplates.Add(new CustomColumnTemplate { columnName = "Value", template = new ButtonColumn(ShowImage, "View Image") }); // This one doesn't works
//}
You used code below:
<Triggers>
<asp:AsyncPostBackTrigger ControlID="mainGrid" />
</Triggers>
According to this article, in asp:AsyncPostBackTrigger If the EventName property is not specified, the DefaultEventAttribute attribute of the control is used to determine the default event. For example, the default event for the Button control is the Click event.
mainGrid control created by GridViewWrapper that it doesn't connected to controls that are in mainGrid.
Updatepanel tries to register async trigger for the mainGrid control which is outside the panel but it can't do it.
solution:
I think solution of this problem is update Updatepanel in ShowImage() method.

How to open Telerik Rad Pop Up window Asynchronously?

I am opening a Telerik RadWindowManager Pop up.
There is a long Database operation to be performed.
During loading i.e. approximately for 35-40 seconds, for the moment, I keep on waiting until the process will come to an end.
Is there any way to load the design first and show a Loader / progress bar to inform the user to wait...Actually the problem gets worse when the Internet speed is slow...
Any suggestion....
Here I have a good example. See here for demo.
aspx file:
<telerik:RadScriptManager id="ScriptManager1" runat="server" />
<telerik:RadAjaxManager ID="RadAjaxManager1" runat="server" OnAjaxRequest="RadAjaxManager1_AjaxRequest"/>
<p>
Press the submit button in order to start monitoring custom progress
</p>
<asp:button ID="buttonSubmit" runat="server" Text="Submit" OnClick="buttonSubmit_Click" CssClass="RadUploadButton" />
<telerik:RadProgressManager id="Radprogressmanager1" runat="server" />
<telerik:RadProgressArea id="RadProgressArea1" runat="server" />
aspx.cs file:
protected void Page_Load(object sender, System.EventArgs e)
{
if (!IsPostBack)
{
//Do not display SelectedFilesCount progress indicator.
RadProgressArea1.ProgressIndicators &= ~ProgressIndicators.SelectedFilesCount;
}
RadProgressArea1.Localization.Uploaded = "Total Progress";
RadProgressArea1.Localization.UploadedFiles = "Progress";
RadProgressArea1.Localization.CurrentFileName = "Custom progress in action: ";
}
protected void buttonSubmit_Click(object sender, System.EventArgs e)
{
UpdateProgressContext();
}
private void UpdateProgressContext()
{
const int total = 100;
RadProgressContext progress = RadProgressContext.Current;
progress.Speed = "N/A";
for (int i = 0; i < total; i++)
{
progress.PrimaryTotal = 1;
progress.PrimaryValue = 1;
progress.PrimaryPercent = 100;
progress.SecondaryTotal = total;
progress.SecondaryValue = i;
progress.SecondaryPercent = i;
progress.CurrentOperationText = "Step " + i.ToString();
if (!Response.IsClientConnected)
{
//Cancel button was clicked or the browser was closed, so stop processing
break;
}
progress.TimeEstimated = (total - i) * 100;
//Stall the current thread for 0.1 seconds
System.Threading.Thread.Sleep(100);
}
}
Now it should be easier to integrate your code.
EDIT: To trigger your Database operation after setting up your RadProgressArea in the PageLoad, you'll need some ajax call to be made after first page load (So I just added the RadAjaxManager to the ascx file upper). Use this code to trigger your DataBase call:
javascript:
function pageLoad(sender, eventArgs) {
if (!eventArgs.get_isPartialLoad()) {
$find("<%= RadAjaxManager1.ClientID %>").ajaxRequest("StartDBOperation");
}
}
ascx.cs file:
protected void RadAjaxManager1_AjaxRequest(object sender, Telerik.Web.UI.AjaxRequestEventArgs e)
{
if (e.Argument == "StartDBOperation")
{
// Start DB operation here..
}
}
Still an Alternative below... But not a solution
I can show a loading panel as follows while the content loads
Mark Up
<div id="loading" style=" width: 100px; height: 50px; display: none;
text-align: center; margin: auto;">
loading...
</div>
<asp:Button ID="RadButton1" runat="server"
Text="RadButton1" OnClientClick="openRadWnd(); return false;" />
<telerik:RadWindowManager ID="RadWindowManager1" runat="server">
<Windows>
<telerik:RadWindow ID="RadWindow1" runat="server"
NavigateUrl="url" ShowContentDuringLoad="false"
OnClientShow="OnClientShow" OnClientPageLoad="OnClientPageLoad">
</telerik:RadWindow>
</Windows>
</telerik:RadWindowManager>
JavaScript
<script type="text/javascript">
var loadingSign = null;
var contentCell = null;
function openRadWnd() {
$find("<%=RadWindow1.ClientID %>").show();
}
function OnClientShow(sender, args) {
loadingSign = $get("loading");
contentCell = sender._contentCell;
if (contentCell && loadingSign) {
contentCell.appendChild(loadingSign);
contentCell.style.verticalAlign = "middle";
loadingSign.style.display = "";
}
}
function OnClientPageLoad(sender, args) {
if (contentCell && loadingSign) {
contentCell.removeChild(loadingSign);
contentCell.style.verticalAlign = "";
loadingSign.style.display = "none";
}
}
</script>
Open the RadWindow with JavaScript on the client, set the desired URL through JavaScript. Performa partial postbacks that do not dispose the RadWindow. If you obtain the URL on the server only - use the same logic, but show the loading sign initially, when the response is done call a script to change the URL of the RadWIndow again.
http://www.telerik.com/help/aspnet-ajax/window-programming-opening.html
http://www.telerik.com/help/aspnet-ajax/window-troubleshooting-javascript-from-server-side.html
http://www.telerik.com/help/aspnet-ajax/window-programming-radwindow-methods.html

Dynamic User Control saving ViewState

I am using a DropDownList to let a user select a form template. The user then posts back to the server and the user controls from the template are dynamically rendered to the page. Once the user fills in the form and clicks save, the ViewState for the user controls are lost and values are empty.
Page Controls
<air:CreateEditForm ID="CreateEditForm" runat="server" />
<asp:PlaceHolder ID="phDynamicControls" runat="server" />
<p>
<asp:Button ID="btnCreate" runat="server" Text="Create" OnClick="btnCreate_Click" CssClass="action-button" />
<asp:Button ID="btnSave" runat="server" Text="Save" OnClick="btnSave_Click" CssClass="action-button" Visible="false" />
<asp:HyperLink ID="linkCancel" runat="server" Text="Cancel" NavigateUrl="Index.aspx" CssClass="action-button" />
</p>
Page Code
protected void btnCreate_Click(object sender, EventArgs e)
{
CreateDynamicSteps();
}
private void CreateDynamicSteps()
{
foreach (WorkflowTemplate workflowTemplate in template.WorkflowTemplates)
{
foreach (WorkflowTemplateStep workflowStep in workflowTemplate.WorkflowTemplateSteps)
{
if (workflowStep.SubSteps.Count > 0)
{
foreach (WorkflowTemplateStep workflowSubStep in workflowStep.SubSteps)
{
if (workflowSubStep.WhoIsDynamic)
{
dynamicSteps.Add(workflowSubStep);
}
}
}
else if (workflowStep.WhoIsDynamic)
{
dynamicSteps.Add(workflowStep);
}
}
}
// removed for brevity
foreach (WorkflowTemplateStep dynamicStep in dynamicSteps)
{
PersonSelectorDialog personSelector = (PersonSelectorDialog)LoadControl("~/Pages/UserControls/PersonSelectorDialog.ascx");
personSelector.ClientIDMode = System.Web.UI.ClientIDMode.Static;
personSelector.LabelID = "lbl" + dynamicStep.ID;
personSelector.Label = dynamicStep.Name + " Selector";
DynamicPersonSelectorDialogs.Add(personSelector);
}
// removed for brevity
}
private void LoadControls()
{
foreach (PersonSelectorDialog personSelector in DynamicPersonSelectorDialogs)
{
Label title = new Label();
title.ID = personSelector.LabelID;
title.ClientIDMode = System.Web.UI.ClientIDMode.Static;
title.Text = personSelector.Label;
phDynamicControls.Controls.Add(title);
phDynamicControls.Controls.Add(personSelector);
}
}
When the user selects the form template from the dropdown and the postback is triggered, that value needs to be retained somewhere because when you perform the second postback you need to load the usercontrol again from the first postback.

Categories

Resources