Values in dynamically added controls not retained on postback - c#

I have a page with a number of controls of type MyControl added dynamically. The count is stored in the ViewState, and only incremented with a button click.
In MyControl, I have a TextBox control, and a Label control. When the text is changed in the textbox, the value is multiplied by 2 and displayed in the label control.
To do this, I have added an OnTextChanged event and set AutoPostBack to true.
My problem is this: when I have any number of MyControl's on the page, and change the text in any of the textboxes, the label is updated and the values are retained on postback.
However, if I click the increment button on the page, all the values in the textboxes and labels are lost.
My code:
Default.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Test.Default" EnableViewState="true" %>
<html>
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
Count:
<asp:Label ID="lblCount" runat="server"></asp:Label>
<asp:Button ID="btnAdd" runat="server" OnClick="btnAdd_Click" Text="+" />
<asp:Panel ID="pnlControls" runat="server"></asp:Panel>
</form>
</body>
</html>
Default.aspx.cs
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
int count = 0;
//if not postback, then set count and store in viewstate
if (!Page.IsPostBack)
{
count = 1;
ViewState["count"] = count;
}
LoadControls();
}
protected void btnAdd_Click(object sender, EventArgs e)
{
//increment count
ViewState["count"] = (int)ViewState["count"] + 1;
pnlControls.Controls.Clear();
LoadControls();
}
private void LoadControls()
{
//add controls to page
for (int i = 0; i < (int)ViewState["count"]; i++)
{
MyControl con = (MyControl)LoadControl("MyControl.ascx");
con.ID = i.ToString();
pnlControls.Controls.Add(con);
}
//set count label
lblCount.Text = ViewState["count"].ToString();
}
}
MyControl.ascx
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="MyControl.ascx.cs" Inherits="Test.MyControl" EnableViewState="true" %>
<div>
<asp:TextBox ID="txtField" runat="server" OnTextChanged="txtField_TextChanged" AutoPostBack="true"></asp:TextBox>
<asp:Label ID="lblAnswer" runat="server" Text="answer:"></asp:Label>
</div>
MyControl.ascx.cs
public partial class MyControl : System.Web.UI.UserControl
{
public string Text;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void txtField_TextChanged(object sender, EventArgs e)
{
lblAnswer.Text = (int.Parse(txtField.Text) * 2).ToString();
}
}
Am I missing something obvious? How can I keep the values when the button is clicked?

The reason you lose the info of MyControl(s..) is when you click the button you clear them:
pnlControls.Controls.Clear();
If you want to keep the values I recomended you to use Session variables, for example an array when you fire "txtField_TextChanged" to save "lblAnswer.Text", be carefull with the ID's to differentiate from each other in the Session variable.
Finally, I'd put "LoadControls();" inside Page_Load, outside I think It's redundant.

Related

Re-Binding Event-Handlers in ASP.NET 4.0 "Templated Control"?

Edit: Sadly, nobody seems to know. Maybe this will help clarify my dilemma: I'm trying to implement my own DataList type of control that supports switching from ItemTemplate to EditItemTemplate. The problem occurs when clicking on a button inside the EditItemTemplate -- it doesn't trigger the handler unless you click a second time!
Sorry about the lengthy post. The code is complete, but hopefully with nothing distracting.
I'm trying to create my own User Control that accepts multiple templates. I'm partly following techniques 39 and 40 from "ASP.NET 4.0 in Practice" by Manning. It seems to be working, except the button inside the template isn't bound to the handler until the second click (after one extra postback).
There are four files involved. Default.aspx:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%# Register Src="~/TheTemplate.ascx" TagPrefix="TT" TagName="TheTemplate" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<TT:TheTemplate ID="tt" runat="server">
<ATemplate>
<p>This is template A</p>
<asp:Button ID="TemplateAButton" OnClick="TemplateAButton_Click" runat="server" Text="Template A Button" />
</ATemplate>
<BTemplate>
<p>This is template B</p>
<asp:Button ID="TemplateBButton" OnClick="TemplateBButton_Click" runat="server" Text="Template B Button" />
</BTemplate>
</TT:TheTemplate>
<br />
<asp:Button ID="ToggleTemplate" Text="Toggle Template" OnClick="ToggleTemplate_Click" runat="server" />
</div>
</form>
</body>
</html>
Default.aspx.cs:
using System;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Trace.IsEnabled = true;
tt.DataBind();
}
protected void ToggleTemplate_Click(object sender, EventArgs e)
{
tt.TemplateName = (tt.TemplateName == "A") ? "B" : "A";
tt.DataBind();
}
public void TemplateAButton_Click(object sender, EventArgs e)
{
Trace.Write("TemplateAButton_Click");
}
public void TemplateBButton_Click(object sender, EventArgs e)
{
Trace.Write("TemplateBButton_Click");
}
}
And the user control, TheTemplate.ascx:
<%# Control Language="C#" AutoEventWireup="true" CodeFile="TheTemplate.ascx.cs" Inherits="TheTemplate" %>
<p>Using template <asp:Literal Text="<%# TemplateName %>" ID="Literal1" runat="server"></asp:Literal></p>
<asp:Placeholder runat="server" ID="PlaceHolder1" />
And finally, TheTemplate.ascx.cs:
using System;
using System.Web.UI;
[ParseChildren(true)]
public class TheTemplateContainer : Control, INamingContainer
{
private TheTemplate parent;
public TheTemplateContainer(TheTemplate parent)
{
this.parent = parent;
}
}
public partial class TheTemplate : System.Web.UI.UserControl, INamingContainer
{
public string TemplateName
{
get { return (string)(ViewState["TemplateName"] ?? "A"); }
set { ViewState["TemplateName"] = value; }
}
[TemplateContainer(typeof(TheTemplateContainer))]
[PersistenceMode(PersistenceMode.InnerProperty)]
public ITemplate ATemplate { get; set; }
[TemplateContainer(typeof(TheTemplateContainer))]
[PersistenceMode(PersistenceMode.InnerProperty)]
public ITemplate BTemplate { get; set; }
protected override void OnDataBinding(EventArgs e)
{
TheTemplateContainer container = new TheTemplateContainer(this);
if (TemplateName == "A")
ATemplate.InstantiateIn(container);
else if (TemplateName == "B")
BTemplate.InstantiateIn(container);
PlaceHolder1.Controls.Clear();
PlaceHolder1.Controls.Add(container);
EnsureChildControls();
base.OnDataBinding(e);
}
}
When you first run it, you will see ATemplate being used:
If you click on the Toggle Template button, all the text is correctly rendered:
But clicking on either "Template A Button" or "Template B Button" will not trigger the OnClick handler on the first try:
It will work on the second click:
Does the problem have to do with where .DataBind() is being called?
I'm not quite sure I understand it, but the problem has to do with how newly-added controls go through the "catch-up" events. Removing PlaceHolder1 and adding it programmatically solves the issue. TheTemplate.ascx becomes:
<%# Control Language="C#" AutoEventWireup="true" CodeFile="TheTemplate.ascx.cs" Inherits="TheTemplate" %>
<p>Using template
<asp:Literal Text="<%# TemplateName %>" ID="Literal1" runat="server"></asp:Literal></p>
... and in TheTemplate.ascx.cs, replace OnDataBinding like this:
protected override void OnDataBinding(EventArgs e)
{
TheTemplateContainer container = new TheTemplateContainer(this);
if (TemplateName == "A")
ATemplate.InstantiateIn(container);
else if (TemplateName == "B")
BTemplate.InstantiateIn(container);
System.Web.UI.WebControls.PlaceHolder PlaceHolder1 = new System.Web.UI.WebControls.PlaceHolder();
//PlaceHolder1.Controls.Clear();
PlaceHolder1.Controls.Add(container);
this.Controls.Clear();
this.Controls.Add(PlaceHolder1);
EnsureChildControls();
base.OnDataBinding(e);
}
In the future, if I ever feel like I need to add controls dynamically, I will also create a PlaceHolder dynamically and use that as the root. When PlaceHolder is populated, I will then add it to the page.

Cannot place dynamically generated textboxes properly using C# in asp.net

I want to load an aspx page having a textbox and a button beside it and with any numeric value in the textbox. On clicking the button beside the textbox I want to generate another set of textbox containing a non-repeating random number and a button beside it and this should continue again if we click the last generated button.
In my code I am getting the output but, in my output the page gets loaded and for the first time it displays a textbox containing '0' and a button but when I click on the generate button it is generating the textboxes and buttons but they are getting placed above the very first textbox containing '0' and rest of all the newly generated textboxes containing with random numbers along with buttons are placed over the first textbox. I want the first textbox to be on the top and rest of them gets generated below it.
I am new to C#, asp.net. Please Help!!!
Following is my code:
<!DOCTYPE html>
<script runat="server">
static int limit = 0;
static int[] x = new int[100];
protected void Page_Load(object sender, EventArgs e)
{
if(Page.IsPostBack)
x[limit] = new Random().Next(100);
}
protected void bGenerate_Click(object sender, EventArgs e)
{
limit++;
}
protected void tbNum_TextChanged(object sender, EventArgs e)
{
//tbNum.Text ="";
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Creates Controls Dynamically</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table style="width:100%;">
<%
for (int counter = 0; counter <= limit; counter++)
{
%>
<tr>
<td>
<input type="text" name="tbNum" id="tbNum" value="<%=x[counter]%>"/>
<%--<asp:TextBox ID="tbNum" runat="server" Width="382px" OnTextChanged="tbNum_TextChanged"></asp:TextBox>--%>
</td>
<td>
<asp:Button ID="bGenerate" runat="server" Text="GENERATE" Width="290px" OnClick="bGenerate_Click" />
</td>
</tr>
<%
}
%>
</table>
</div>
</form>
</body>
You should move the code that generates new random values to the bGenerate_Click event:
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
x[0] = new Random().Next(100);
}
protected void bGenerate_Click(object sender, EventArgs e)
{
limit++;
x[limit] = new Random().Next(100);
}
The problem with your existing code is that when you click on the Generate button, the code in Page_Load is executed before bGenerate_Click.

tooltip computed links for asp button after button is clicked

<ItemTemplate>
<tr>
<asp:LinkButton ID="btnID" runat="server"
ToolTip='The calculated IDs are: ' OnCommand="showIds"
CommandArgument='<%# Convert.ToInt32(Eval("Year")) + "," +
Convert.ToInt32(Eval("Month")) %>'>
<%# Convert.ToInt32(Eval("Count")) - Convert.ToInt32(Eval("LittleCount"))%>
</asp:LinkButton>
</tr>
</ItemTemplate>
As you can notice the tooltip text is static. In code behind, I do calculate and get some integers ( IDs ) every time the above button is clicked ( protected void showIds(object sender, CommandEventArgs e) { .... }) contained as a List<ExpressionListDictionary>. ( the asp:LinkButton is contained inside an asp:ListView )
What I want to do, is to change the tooltip into a dynamic one, containing all the already obtained IDs as links. ( Something like this: http://jsfiddle.net/IrvinDominin/jLkcs/5/ - but in my case I do need firstly to click the button for calculating the IDs, and after this I would need to change the tooltip text from code as it needs to show the respective IDs, as links if it is possible)
How can I achieve this?
If you have a class (or id or something) to identify the buttons you can make an jQuery document ready function to change the tooltip with ids to a link containing the ids.
I modifyed your fiddle: http://jsfiddle.net/jLkcs/545/
$(document).ready(function () {
$(".myLinkButton").each(function() {
createlink(this);
});
});
function createlink(obj){
var ids= $(obj).attr('title');
var linkHtml="<a href='javascript:alert(" + ids + ")'>link</a>"
$(obj).attr('title',linkHtml);
}
Why not simply adjust the ToolTip in the codebehind during postback?
protected void showIds(object sender, CommandEventArgs e)
{
((LinkButton)sender).ToolTip = "blahblah";
}
You can set your sender attributes if the CommandEventArgs CommandName is equal with your defined one
public void LinkButton_Command(Object sender, CommandEventArgs e)
{
if (e.CommandName.Equals("showIds"))
{
//
}
}
Here is an working example, this will work, not counting in what user control LinkButton is used:
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : Page
{
public string btnNoTooltip = "No IDs are calculated";
public string btnTooltip = "The calculated IDs are:";
protected void Page_Load(object sender, EventArgs e)
{
}
public void LinkButton_Command(Object sender, CommandEventArgs e)
{
if (e.CommandName.Equals("LinkButtonOrder"))
{
LinkButton lkTrigger = (LinkButton)sender;
if (lkTrigger.ToolTip.Equals(btnNoTooltip))
{
lkTrigger.ToolTip = btnTooltip + " " + e.CommandArgument;
}
else
{
lkTrigger.ToolTip += " " + e.CommandArgument;
}
Random random = new Random();
lkTrigger.CommandArgument = random.Next(0, 100).ToString();
Label1.Text = "Triggered: " + e.CommandName + " with Argument " + e.CommandArgument;
}
}
}
Markup:
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<h3>LinkButton Command Event Example</h3>
<asp:LinkButton id="LinkButton1"
Text="Order Item Here"
CommandName="LinkButtonOrder"
ToolTip='No IDs are calculated'
CommandArgument="01"
OnCommand="LinkButton_Command"
runat="server"/>
<br />
<asp:LinkButton id="LinkButton2"
Text="Or Order Item Here"
CommandName="LinkButtonOrder"
CommandArgument="02"
ToolTip='No IDs are calculated'
OnCommand="LinkButton_Command"
Runat="server"/>
<br />
<br />
<asp:Label id="Label1" runat="server"/>
<asp:PlaceHolder id="plhInjectId" runat="server" Visible="false"></asp:PlaceHolder>
</asp:Content>
You can use jquery to generate Tool Tip on Page itself.
Add a hidden field for your all the already obtained IDs (comma sepearted) to asp:ListView
Populate this hidden in ItemCreated event on server
add a class to your link button, say 'ShowHyperlinkOnHover'
Bind mouseenter event to class ShowHyperlinkOnHover document.ready function of jquery, this will dynamically generate tool tip. and then on Mouse Over tool tip will be displayed.
$(document).ready(function () {
$(document).on("mouseenter", ".ShowHyperlinkOnHover", function(this){
// 2 is index of hidden field having comma seperated Ids
var dynaToolTip;
$(this).parent("td:nth-child(2)").split(',').each(
function(oneId) dynaToolTip=dynaToolTip+ anyFomationLogic(oneId);
);
$(this).attr('title',dynaToolTip);
});
});

Loading a dynamically created radio button list

I am trying to generate a dynamic radio button list, but the issue is that the dynamic list does not show on page load. Only the Submit button shows. Here is the code I am using:
<asp:PlaceHolder runat="server" ID="PlaceHolder1"/>
<asp:Button runat="server" ID="Button1" OnClick="Button1_Click" Text="Submit" />
<asp:Label runat="server" ID="Label1"/>
protected void Page_Load(object sender, EventArgs e)
{
LoadControls();
}
protected void Button1_Click(object sender, EventArgs e)
{
var radioButtonList = PlaceHolder1.FindControl("1") as RadioButtonList;
Label1.Text = radioButtonList.SelectedValue;
}
private void LoadControls()
{
var tmpRBL = new RadioButtonList();
tmpRBL.ID = "1";
for (int i = 1; i <= 5; i++)
{
var tmpItem = new ListItem(i.ToString(), i.ToString());
tmpRBL.Items.Add(tmpItem);
}
PlaceHolder1.Controls.Add(tmpRBL);
}
WebForm1.aspx
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:PlaceHolder runat="server" ID="PlaceHolder1"/>
<asp:Button runat="server" ID="Button1" OnClick="Button1_Click" Text="Submit" />
<asp:Label runat="server" ID="Label1"/>
</div>
</form>
</body>
</html>
WebForm1.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
LoadControls();
}
protected void Button1_Click(object sender, EventArgs e)
{
var radioButtonList = PlaceHolder1.FindControl("1") as RadioButtonList;
Label1.Text = radioButtonList.SelectedValue;
}
private void LoadControls()
{
var tmpRBL = new RadioButtonList();
tmpRBL.ID = "1";
for (int i = 1; i <= 5; i++)
{
var tmpItem = new ListItem(i.ToString(), i.ToString());
tmpRBL.Items.Add(tmpItem);
}
PlaceHolder1.Controls.Add(tmpRBL);
}
}
}
It works correct. I hope it will be helpful.
You could define an empty RadioButtonList control which you then populate with items on Page_Load. Would have the advantage that you don't have to create it manually. Also using the DataBind mechanism the control offers you together with an ObjectDataSource is a better solution (the Select method of the ObjectDataSource should return the items).
But aside this, maybe AutoEventWireup of the #Page directive (first line in the markup of the ASPX page) is set to false. If so the Page_Load event handler is not called. The directive usually looks like this:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>
I copied the rest of your code and everything runs just fine.

Repeater and Custom Control - Dynamically adding to the collection and retaining values

It has been so long since I've used Web Forms I find myself not remembering most of the perks.
I have a user control that has a button, a repeater and the ItemTemplate property of the repeater is another user control.
<asp:Button runat="server" ID="btnAdd" CssClass="btn" Text="Add" OnClick="btnAdd_Click"/>
<br/>
<asp:Repeater runat="server" ID="rptrRequests">
<ItemTemplate>
<uc1:ucRequest ID="ucNewRequest" runat="server" />
</ItemTemplate>
</asp:Repeater>
The idea is that when the user clicks on the Add button a new instance of the ucRequest is added to the collection. The code behind is as follows:
public partial class ucRequests : UserControl
{
public List<ucRequest> requests
{
get
{
return (from RepeaterItem item in rptrRequests.Items
select (ucRequest) (item.Controls[1])
).ToList();
}
set
{
rptrRequests.DataSource = value;
rptrRequests.DataBind();
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack) return;
requests = new List<ucRequest>();
}
protected void btnAdd_Click(object sender, EventArgs e)
{
var reqs = requests;
reqs.Add(new ucRequest());
requests = reqs;
}
}
After much googling I now remember that I should be binding the Repeater in the OnInit method in order for the ViewState to put the captured data of the controls within the ucRequest control on them between post backs but when I try to do that I will always have a single instance of the control on the Repeater since its Items collection is always empty.
How could I manage to do this?
Thanks in advance.
You just need control ids in view state stead of entire control collection.
<%# Control Language="C#" AutoEventWireup="true"
CodeBehind="ucRequests.ascx.cs"
Inherits="RepeaterWebApplication.ucRequests" %>
<asp:Button runat="server" ID="btnAdd" CssClass="btn" Text="Add"
OnClick="btnAdd_Click" />
<br /><asp:PlaceHolder runat="server" ID="PlaceHolder1"></asp:PlaceHolder>
<%# Control Language="C#" AutoEventWireup="true"
CodeBehind="ucRequest.ascx.cs"
Inherits="RepeaterWebApplication.ucRequest" %>
<asp:TextBox runat="server" ID="TextBox1"></asp:TextBox>
private List<int> _controlIds;
private List<int> ControlIds
{
get
{
if (_controlIds == null)
{
if (ViewState["ControlIds"] != null)
_controlIds = (List<int>) ViewState["ControlIds"];
else
_controlIds = new List<int>();
}
return _controlIds;
}
set { ViewState["ControlIds"] = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
foreach (int id in ControlIds)
{
Control ctrl = Page.LoadControl("ucRequest.ascx");
ctrl.ID = id.ToString();
PlaceHolder1.Controls.Add(ctrl);
}
}
}
protected void btnAdd_Click(object sender, EventArgs e)
{
var reqs = ControlIds;
int id = ControlIds.Count + 1;
reqs.Add(id);
ControlIds = reqs;
Control ctrl = Page.LoadControl("ucRequest.ascx");
ctrl.ID = id.ToString();
PlaceHolder1.Controls.Add(ctrl);
}
Try to get the ucRequests during the OnItemDatabound event, at that point you can edit the content of itemtemplate of the repeater. You can get there after the postback caused by the click on the add button. Here's a sample with a similar scenario

Categories