Programmatically Adding User Controls Inside An UpdatePanel - c#

I'm having trouble dynamically adding controls inside an update panel with partial postbacks. I've read many articles on dynamic controls and I understand how to add and maintain them with postbacks but most of that information doesn't apply and won't work for partial postbacks. I can't find any useful information about adding and maintaining them with UpdatePanels. I'd like to do this without creating a web service if it's possible. Does anyone have any ideas or references to some helpful information?

This is, I think, one of the common pitfalls for asp.net programmers but isn't actually that hard to get it right when you know what is going on (always remember your viewstate!).
the following piece of code explains how things can be done. It's a simple page where a user can click on a menu which will trigger an action that will add a user control to the page inside the updatepanel.
(This code is borrowed from here, and has lots more of information concerning this topic)
<%# Page Language="C#" AutoEventWireup="true" CodeFile="SampleMenu1.aspx.cs" Inherits="SampleMenuPage1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Sample Menu</title>
</head>
<body>
<form id="form1" runat="server">
<asp:Menu ID="Menu1" runat="server" OnMenuItemClick="Menu1_MenuItemClick">
<Items>
<asp:MenuItem Text="File">
<asp:MenuItem Text="Load Control1"></asp:MenuItem>
<asp:MenuItem Text="Load Control2"></asp:MenuItem>
<asp:MenuItem Text="Load Control3"></asp:MenuItem>
</asp:MenuItem>
</Items>
</asp:Menu>
<br />
<br />
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Menu1" />
</Triggers>
</asp:UpdatePanel>
</form>
</body>
</html>
and
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class PlainSampleMenuPage : System.Web.UI.Page
{
private const string BASE_PATH = "~/DynamicControlLoading/";
private string LastLoadedControl
{
get
{
return ViewState["LastLoaded"] as string;
}
set
{
ViewState["LastLoaded"] = value;
}
}
private void LoadUserControl()
{
string controlPath = LastLoadedControl;
if (!string.IsNullOrEmpty(controlPath))
{
PlaceHolder1.Controls.Clear();
UserControl uc = (UserControl)LoadControl(controlPath);
PlaceHolder1.Controls.Add(uc);
}
}
protected void Page_Load(object sender, EventArgs e)
{
LoadUserControl();
}
protected void Menu1_MenuItemClick(object sender, MenuEventArgs e)
{
MenuItem menu = e.Item;
string controlPath = string.Empty;
switch (menu.Text)
{
case "Load Control2":
controlPath = BASE_PATH + "SampleControl2.ascx";
break;
case "Load Control3":
controlPath = BASE_PATH + "SampleControl3.ascx";
break;
default:
controlPath = BASE_PATH + "SampleControl1.ascx";
break;
}
LastLoadedControl = controlPath;
LoadUserControl();
}
}
for the code behind.
That's basically it. You can clearly see that the viewstate is being kept with LastLoadedControl while the controls themselves are dynamically added to the page (inside the updatePanel (actually inside the placeHolder inside the updatePanel) when the user clicks on a menu item, which will send an asynchronous postback to the server.
More information can also be found here:
http://aspnet.4guysfromrolla.com/articles/081402-1.aspx
http://aspnet.4guysfromrolla.com/articles/082102-1.aspx
and of course on the website that holds the example code I used here.

I encountered the problem that using the method mentioned above, LoadUserControl() is called twice when handling an event. I've read through some other articles and would like to show you my modification:
1) Use LoadViewstate instead of Page_Load to load the user control:
protected override void LoadViewState(object savedState)
{
base.LoadViewState(savedState);
if (!string.IsNullOrEmpty(CurrentUserControl))
LoadDataTypeEditorControl(CurrentUserControl, panelFVE);
}
2) Don't forget to set the control id when loading the usercontrol:
private void LoadDataTypeEditorControl(string userControlName, Control containerControl)
{
using (UserControl myControl = (UserControl) LoadControl(userControlName))
{
containerControl.Controls.Clear();
string userControlID = userControlName.Split('.')[0];
myControl.ID = userControlID.Replace("/", "").Replace("~", "");
containerControl.Controls.Add(myControl);
}
this.CurrentUserControl = userControlName;
}

Try this:
Literal literal = new Literal();
literal.Text = "<script type='text/javascript' src='http://www.googleadservices.com/pagead/conversion.js'>";
UpdatePanel1.ContentTemplateContainer.Controls.Add(literal);
You can replace the content of literal with any HTML content you want...

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.

Find A Control (Inside Master Page) From Content Page, Error = NullReferenceException

Please See The Simple Example Below For Understanding My situation.
(Attention To Comments Inside Codes)
Master Page (ASPX) :
<%# Master Language="C#" AutoEventWireup="true" CodeBehind="Site1.master.cs" Inherits="NiceFileExplorer.Site1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<asp:ContentPlaceHolder ID="head" runat="server">
</asp:ContentPlaceHolder>
</head>
<body>
<form id="form1" runat="server">
<div>
<span runat="server" id="SummaryContainer">
<asp:Label ID="lblDownload_Count_By_UserID_Today_Title" runat="server" Text="Count :"
ToolTip="Your Download Count-Today" CssClass="lblTitleInStatistics_Master"></asp:Label>
<asp:Label ID="lblDownload_Count_By_UserID_Today" runat="server" Text="<%# Download_Count_By_UserID_Today() %>"
CssClass="lblCountInStatistics_Master" ToolTip="Your Download Count-Today"></asp:Label>
<span style="color: white;"> | </span>
<asp:Label ID="lblDownload_Size_By_UserID_Today_Title" runat="server" Text="Size :"
ToolTip="Your Download Size-Today" CssClass="lblTitleInStatistics_Master"></asp:Label>
<asp:Label ID="lblDownload_Size_By_UserID_Today" runat="server" Text="<%# Download_Size_By_UserID_Today() %>"
CssClass="lblCountInStatistics_Master" ToolTip="Your Download Size-Today"></asp:Label>
</span>
</div>
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server" ViewStateMode="Inherit" ClientIDMode="Static">
</asp:ContentPlaceHolder>
</div>
</form>
</body>
</html>
as you see i set ClientIDMode="Static".
Master Page (CodeBehind) :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace NiceFileExplorer
{
public partial class Site1 : System.Web.UI.MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
SummaryContainer.DataBind();
}
protected string Download_Count_By_UserID_Today()
{
//Read New Count From DataBase
//return Count;
return "Test";
}
protected string Download_Size_By_UserID_Today()
{
//Read New Size From DataBase
//return Size;
return "Test";
}
}
}
Content Page (ASPX) :
<%# Page Title="" Language="C#" MasterPageFile="~/Site1.Master" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="NiceFileExplorer.WebForm1" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
Conntent Page
</asp:Content>
Content Page (CodeBehind) :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace NiceFileExplorer
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
MyMethod();
}
private void MyMethod()
{
//Add New Downloaded File Info To DataBase(); -> For Getting Count And Size Of Them Per Day
//Here I Wand To Access Master Page Controls And Update Count And Size Lables
//So, I Tried Codes Below Without Any Results -> How Can I Fix This ?
var SummaryContainer = (System.Web.UI.HtmlControls.HtmlGenericControl)Page.Master.FindControl("SummaryContainer");
SummaryContainer.DataBind();
SummaryContainer.InnerHtml = "<h2>Hello World</h2>";
//After Update Those Lables Failed, I test the codes Below With Null Execption Error -> How Can I Fix This ?
var lblDownload_Count_By_UserID_Today_Title = (Label)Page.Master.FindControl("lblDownload_Count_By_UserID_Today_Title");
lblDownload_Count_By_UserID_Today_Title.Text = "test";
DwonloadFile();
}
private void DwonloadFile()
{
//A Class (Method) That Shows Download Window To My Users, So Page_Load Of Master Will Never Fire...
//And This Is The Reason That I want to update count & size lables from content page
}
}
}
i want to DataBind SummaryContainer(a span) from content page's code-behind.
so i tried the codes below :
var SummaryContainer = (System.Web.UI.HtmlControls.HtmlGenericControl)Page.Master.FindControl("SummaryContainer");
SummaryContainer.DataBind():
but i can not see new results.
After That Fail I tried to find a label's text(that label is inside Master) from content page code behind for test like below : var
lblDownload_Count_By_UserID_Today_Title = (Label)Page.Master.FindControl("lblDownload_Count_By_UserID_Today_Title");
lblDownload_Count_By_UserID_Today_Title.Text = "test";
but i have System.NullReferenceException ERROR :
Object reference not set to an instance of an object.
how can i fix that error and force that span to show me new results?
thanks in advance
In a project I used an interface on the masterpage:
((IMasterPage)Page.Master).MyProperty = "test";
But in your case, personally instead of putting all that on the master page, I'd put your SummaryContainer into a UserControl, and have another ContentPlaceHolder.
Then the Page_Load method will be able to access the properties, and on future pages you could have different summary info by filling that first PlaceHolder with a different UserControl.
Also debugging stupid errors, is the Null exception being thrown at .Master.FindControl or at lbl.Text?
I'm unable to debug it for myself right now, but would it be due to the page life cycle, namely that Content Page Load comes before Master Page Load?

submit button click

I have GUI for data acceptance.
I need to pass all the parameters of the form on click of a submit button to a function declared in C#.
Please help.
Using .Net us have too types of submit tags, one starting with <asp: and the other starting with <input. the <input html tag can call javascript and if you add the runat="server" attribute, you will enable it to also have C# code behind the button.
First of all, you will need to create an aspx page (say submission.aspx) that will receive the POST submission of your form. In that page, you can include your .cs file that contains the method/function you want to pass the data to.
Next, you want to submit you submit your data to submission.aspx. To do that, you will need to have a form which will submit its data to submission.aspx.
<form action='submission.aspx' method='POST' id='data-submission'>
<!-- stuff here -->
</form>
If you want to perform ajax submission, you can use jquery and use this code:
$('#data-submission').submit(function(evt){
var $form = $(this);
var url = $form.attr('action');
$.post(url, $form.serialize(), function(){alert('submission complete!);});
});
I wonder if all that helped you.
PS: I haven't used .NET for web programming in a long time now.. but what I've written here in this answer hold universally true for any web programming language/framework.
If your using asp.net you just need to double click the button(if it is an asp button) and it should make a click event.
In the click event you could get your other controls like
default.aspx code
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</div>
</form>
</body>
</html>
Codebehind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
// you can declare it as a field variable so the entire code behind can use it
private Passengerdetails myClass;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
// create an instance of the class.
myClass = new Passengerdetails ();
// stick textbox1 contents in the property called test.
myClass.PassengerName = TextBox1.Text;
int a = Convert.ToInt32(TextBox1.Text);
int b = Convert.ToInt32(TextBox2.Text);
int sum = Add(a, b);
// do something with it like return it to a lbl.
Label1.Text = sum.ToString();
}
private int Add(int a, int b)
{
return a + b;
}
}
Edit. You just make a class.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
/// <summary>
/// Summary description for passengerdetails
/// </summary>
public class Passengerdetails
{
public Passengerdetails ()
{
public string PassengerName{ get; set; }
}
}

Dynamically create a ASP.net Submit LinkButton using a Panel

I am trying to implement an application which will dynamically create a list with a button next to each item on that list. I am partially able to do this using the Panel control in the aspx page and adding html dynamically in the code behind. I am having problems adding the LinkButton dynamically which will do database work based on which ID it is. Is this even possible with what I have?:
aspx:
<asp:Panel ID="ItemPanel" runat="server">
</asp:Panel>
code behind:
...
StringBuilder sb = new StringBuilder();
string UserID;
while (dr.Read())
{
UserID = Convert.ToInt32(dr["UserID"]);
sb.Append("<div><b class='template'></b>");
//Create LinkButton with event and code behind function
}
ItemPanel.Controls.Add(new LiteralControl(sb.ToString()));
You may want to take a look at this very recent question and if you have additional queries, then edit your question.
Edit (after OP's comment)
The purpose of posting that link was to give you an idea how to create the control dynamically. Since you ask, here's a simple bare-bones ASPX page that creates a LinkButton and attaches an eventhandler for the Click event. Not sure what you mean by "handle changes on the server", though.
<%# Page Language="C#" %>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
LinkButton lnk1 = new LinkButton();
lnk1.Text = "Click me!";
//lnk1.PostBackUrl = "SomeOtherPage.aspx";
// Use the eventhandler to perform redirection,
// instead of the PostBackUrl to show it works.
lnk1.Click += new EventHandler(lnk1_Click);
// Add control to container:
pnl1.Controls.Add(lnk1);
}
void lnk1_Click(object sender, EventArgs e)
{
Response.Redirect("SomeOtherPage.aspx");
}
</script>
<html>
<head>
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<asp:Panel ID="pnl1" runat="server">
</asp:Panel>
</form>
</body>
</html>

Prevent Multi-Line ASP:Textbox from trimming line feeds

I have the following webform:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"
Inherits="TestWebApp.Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtMultiLine" runat="server"
Width="400px" Height="300px" TextMode="MultiLine"></asp:TextBox>
<br />
<asp:Button ID="btnSubmit" runat="server"
Text="Do A Postback" OnClick="btnSubmitClick" />
</div>
</form>
</body>
</html>
and each time I post-back the leading line feeds in the textbox are being removed. Is there any way that I can prevent this behavior?
I was thinking of creating a custom-control that inherited from the textbox but I wanted to get a sanity check here first.
I ended up doing the following in the btnSubmitClick()
public void btnSubmitClick(object sender, EventArgs e)
{
if (this.txtMultiLine.Text.StartsWith("\r\n"))
{
this.txtMultiLine.Text = "\r\n" + this.txtMultiLine.Text;
}
}
I must be really tired or sick or something.
I think that the problem here is in the way that the browser renders the textarea contents, not with ASP.NET per se. Doing this:
public void btnSubmitClick(object sender, EventArgs e) {
this.txtMultiLine.Text = "\r\n" + this.txtMultiLine.Text;
}
will let you reach the desired screen output, but you'll add an extra newline to the Text that the user didn't enter.
The ideal solution would be for the TextBox control in ASP.NET to always write the newline AFTER writing the open tag and BEFORE writing the contents of Text. This way, you'd reach the desired effect without trumping the contents of the textbox.
We could inherit from TextBox and fix this by overriding RenderBeginTag:
public override void RenderBeginTag(HtmlTextWriter writer) {
base.RenderBeginTag(writer);
if (this.TextMode == TextBoxMode.MultiLine) {
writer.Write("\r\n"); // or Environment.NewLine
}
}
Now, creating a new class for this small issue seems really overkill, so your pragmatic approach is completely acceptable. But, I'd change it to run in the PreRender event of the page, which is very late in the page lifecycle and would not interfere with the processing of the submitted text in the OnSubmit event of the button:
protected void Page_Load(object sender, EventArgs e) {
this.PreRender += Page_OnPreRender;
}
protected void Page_OnPreRender(object sender, EventArgs e) {
this.txtMultiLine.Text = "\r\n" + this.txtMultiLine.Text;
}

Categories