Showing posts with label control. Show all posts
Showing posts with label control. Show all posts

Wednesday, March 28, 2012

Progess bar for a fileupload in an iFrame

hi,

I have put a file upload control in an iFrame so that I can mimic an asynch. postback. This works well, but now I would like to be able to detect when the button in the iFrame that submits the form in the iframe is clicked, so that i can trigger a "processing" message in the main page, which isn't posting back.

Any ideas on how I might accomplish this? (or if anyone has a better way to do an asynchrounous fileupload I'm very open to suggestions :-)

Hmm... I would be very interested in the direction you are headed.

Couldn't you do something with the onclientclick of the submit button in the iframe? So when that submit button is clicked in the iframe, a javascript is fired in the parent/main page that shows a "processing" message.

http://www.esqsoft.com/javascript_examples/iframe_talks_to_parent/

I am trying to do the exact same thing, would you have any example code?

thanks..

Programatically add UserControls that Contain an UpdatePanel

In the release notes for the latest release it states that you can programatically add UpdatePanels now. I have a user control (ascx) that contains an UpdatePanel and a Timer to refresh the panel. When I add more than one of these controls to the page programatically the first refresh of one of the UpdatePanels blanks out all of the data in all of ascx controls. When I add the controls to the page in the aspx code everything works fine. I need to add them programatically since the number of them is configurable. I have the ScriptManager control on the page with partial refresh enabled. Is there something special I need to do when I add these controls programatically?

UserControl

<%@dotnet.itags.org. Control Language="C#" AutoEventWireup="true" Codebehind="DataPart.ascx.cs" Inherits="MS.Support.KnowledgeManagement.VisualKb.DataPart"
EnableViewState="false" %>
<div class="dataPart">
<div id="divHeader" class="dataPartHeader" runat="server">
<img alt="Collapse" style='float: right' src='images/Collapse.gif' title='Collapse'
onclick="ExpandCollapse(this,this.parentElement.parentElement.children(1))" />
<asp:Label ID="lblHeader" runat="server"></asp:Label>
</div>
<div id="divBody" class="dataPartBody" runat="server">
<asp:UpdatePanel ID="divUpdate" UpdateMode="Conditional" runat="server">
<ContentTemplate>
<vkb:VkbBulletedList ID="blItems" runat="server" BulletStyle='disc' DisplayMode='HyperLink'
CssClass="dataPartList" NewIndicatorFontColor="red">
</vkb:VkbBulletedList>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="timerRefresh" />
</Triggers>
</asp:UpdatePanel>
<div style='text-align: center; width: 100%'>
<asp:HyperLink ID="lnkViewAll" runat="server" CssClass="dataPartLink">View All</asp:HyperLink>
</div>
</div>
</div>
<asp:XmlDataSource ID="xmlDataSource" runat="server" XPath="descendant::Items/Item"
EnableCaching="false" EnableViewState="False"></asp:XmlDataSource>
<asp:Timer ID="timerRefresh" OnTick="timerRefresh_Tick" runat="server">
</asp:Timer>

Code to add ascx to page

dp = Page.LoadControl("DataPart.ascx") as DataPart;
dp.DataType = "Article";
dp.HeaderColor = Color.LightGray;
dp.HeaderFontColor = Color.Black;
dp.HeaderText = nodes.Current.GetAttribute("Name", String.Empty);
dp.CategoryId = Convert.ToInt32(nodes.Current.GetAttribute("Id", String.Empty));
dp.BodyColor = Color.WhiteSmoke;
dp.EnableRefresh = false;
dp.XmlData = nodes.Current.SelectSingleNode("Items") != null ? nodes.Current.SelectSingleNode("Items").OuterXml : "<Items />";
td.Controls.Add(dp);

I tried a simple example just using a RadioButtonList against XML data source and everything seemed to work fine when adding dynamically. What's in the VkbBulletedList control?
Its just an override of the BulletedList control to add some custom text to each bulleted item.

Programatically Adding an AutoCompleteExtender & AutoCompleteProperties

This is from the documentation:

To extend a text box with auto-completion behavior programmatically, add an AutoCompleteExtender control to your ASP.NET Web page, and use theServicePath andServiceMethod properties to specify the Web method that returns the item list. Then for each text box that you want to add the auto-completion behavior to,add anAutoCompleteProperties server control to theControls collection of the AutoCompleteExtender. The AutoCompleteProperities component enables you to specify the target control the extender should link to and to override the ServicePath and ServiceMode setting for individual controls.

So am I to understand that I add an AutoCompleteProperties instance to the AutoCompleteExtender.Controls collection?

When I try that I get this message in VS2005:

Value of type 'Microsoft.Web.UI.Controls.AutoCompleteProperties' cannot be converted to 'System.Web.UI.Control'.

hello.

well, you just need to add them as child elements of the control since it'll automaticatically parse those elements and add them to the targetproperties property.


...forgive me for my ignorance, but how exactly is that accomplished? Can you provide a brief example?

Thanks! :)


Dim autoComplete as New AutoCompleteExtender()
Dim props as New AutoCompleteProperties()
props.TargetControlID = "txt_suggestion"
props.ServiceURL = "/WebServices/Service.asmx"
props.ServiceMethod = "GetSuggestions"
autoComplete.TargetProperties.Add(props)
Page.Controls.add(autoComplete)

Hey that worked! Thanks!

I didn't know about the AutoCompleteExtender.TargetProperties.Add method, I was trying to add it to the controls collection of the AutoCompleteExtender.

FYI - The ServiceURL property in the above code is supposed to be ServicePath (at least in the July 06 release).

Programatically adding UpdatePanel?

I want to programatically add an updatepanel control on a button click.

I tried adding a reference to Microsoft.Web.Atlas.dll and then creatinga System.Web.UI.UpdatePanel control but the app does not compile - withnamespace does not exist error.

Does anyone know what I should be doing or if this is possible at all?

Thanks !

you would need to import the following

Imports Microsoft.Web.UI

Then, you can create an instance of the UpdatePanel like this:

Dim UP As New UpdatePanel

Hope this works for you.


Thanks it works ... I was using System.Web.UI which was the problem
Now that I have this I'm trying to add content to the updatepanel.

I can set most of the properties, add triggers without problems.

However when I try to execute it - it gives an error saying "A ContentTemplate must be specified".

Whats the easist way to do this. I haven't found any documentation on programatically adding a contenttemplate.

Any help would be greatly appreciated!
I'm looking for the same thing myself and haven't found any answers.
You'll need to create a class that implements ITemplate, create an instance of that and set the content template property to that instance.

try this

protected

overridevoid OnInit(EventArgs e)

{

updatePanel.ContentTemplate =

newCompiledTemplateBuilder

(

newBuildTemplateMethod(CreateAtlasUpdateContent));

}

public

void CreateAtlasUpdateContent(Control container)

{

container.Controls.Add(yourcontrol);

}


dont know if this will come in handy with anyone but what i did to get around the template error was

have a class with the following:

PublicClass AjaxControl :Inherits Microsoft.Web.UI.UpdatePanelProtectedOverridesSub OnInit(ByVal eAs System.EventArgs)Me.ContentTemplate =New TemplateBuilderMyBase.OnInit(e)EndSubEndClass

Then whenever i needed to create a control that was surrounded by the update panel i would inherit this class and could just then put me.controls.add() as usual.

probs useless to you all, but works for me :)


Even if you got past the coding issues, you still can't add an UpdatePanel once InitComplete has fired (which is pretty early in the lifecycle) so you're not going to be able to accomplish what you set out to do, which I think was to add an UpdatePanel dynamically.

HTH

Has anyone been able to dynamically add an UpdatePanel to a page?

I got so far - and then I got the error:

"The UpdatePanel 'panel1'was not present when the page's InitComplete event was raised."

Is there any way around this?

Wade.

Programatically set ImageUrl in ModalPopup

Hi I have a DataList that populates from an SQL datasource. One control in the DataList is an image whose ImageUrl i am currently setting as follows:

protected void dlItems_ItemDataBound(object sender, DataListItemEventArgs e)
{
Label lblItemID = (Label)e.Item.FindControl("lblItemID");
Image imgItem = (Image)e.Item.FindControl("imgItem");

imgItem.ImageUrl ="~/Images/Items/" + lblItemID.Text +".jpg";
}


I want to be able to click the image and get a modal popup which displays a large view of the image. I have wrapped the image (imgItem) in a LinkButton. Heres the code:

<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<script runat="server">
[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod]
public void SetLargeImagePath(int contextKey)
{
imgLargeImage.ImageUrl = "~/Images/Items/" + contextKey.ToString() + ".jpg";
}
</script>
<div>
<asp:DataList ID="dlItems" runat="server" DataKeyField="pkiItemID" Width="100%" OnItemDataBound="dlItems_ItemDataBound">
<ItemTemplate>
<asp:Label ID="lblItemID" runat="server" Text='<%# Eval("pkiItemID")%>' Visible="False" CssClass="ItemText"></asp:Label>
<asp:Label ID="bSpecialOfferLabel" runat="server" Text='<%# Eval("bSale")%>' Visible="False" CssClass="ItemText"></asp:Label>
<table width="100%" class="Table">
<tr>
<td rowspan="6" valign="top">
<asp:LinkButton ID="lnkImage" runat="server">
<asp:Image ID="imgItem" runat="server" Width="150px" AlternateText="Click for a larger view" />
</asp:LinkButton>
<cc1:ModalPopupExtender ID="ModalPopupExtender" runat="server" TargetControlID="lnkImage" PopupControlID="pnlLargeImage"
BackgroundCssClass="modalBackground"
OkControlID="OkButton" DynamicControlID="Label1" DynamicContextKey='<%# Eval("pkiItemID")%>' DynamicServiceMethod="SetLargeImagePath" >
</cc1:ModalPopupExtender>
</td>
<td style="width: 104px; padding-left: 5px;"><h2>Title:</h2></td>
<td><asp:Label ID="szTitleLabel" runat="server" Text='<%# Eval("szTitle")%>' CssClass="ItemText"></asp:Label></td>
<td style="width: 112px" rowspan="6" valign="middle">
</td>
</tr>
<tr>
<td style="width: 104px; padding-left: 5px;"><h2>Type:</h2></td>
<td><asp:Label ID="szItemTypeLabel" runat="server" Text='<%# Eval("szItemType")%>' CssClass="ItemText"></asp:Label></td>
</tr>
<tr>
<td style="width: 104px; padding-left: 5px;"><h2>Status:</h2></td>
<td><asp:Label ID="szItemStatusLabel" runat="server" Text='<%# Eval("szItemStatus")%>' CssClass="ItemText"></asp:Label></td>
</tr>
<tr>
<td style="width: 104px; padding-left: 5px;"><h2>Description:</h2></td>
<td><asp:Label ID="szDescriptionLabel" runat="server" Text='<%# Eval("szDescription")%>' CssClass="ItemText"></asp:Label></td>
</tr>
<tr>
<td style="width: 104px; padding-left: 5px;"><h2>Price:</h2></td>
<td><asp:Label ID="mPriceLabel" runat="server" Text='<%# String.Format("{0:c}", Eval("mPrice"))%>' CssClass="ItemText"></asp:Label></td>
</tr>
<tr>
<td style="width: 104px; padding-left: 5px;"><h2><asp:Label ID="mOfferPriceLabelStatic" runat="server" Text="Offer Price:"></asp:Label></h2></td>
<td><asp:Label ID="mOfferPriceLabel" runat="server" Text='<%# String.Format("{0:c}", Eval("mSalePrice"))%>' CssClass="ItemText"></asp:Label></td>
</tr>
<tr>
<td align="center" colspan="4">
<asp:Button ID="btnAddToBasket" runat="server" CssClass="Button" Text="Add To Basket" />
<asp:Button ID="btnBuyNow" runat="server" CssClass="Button" Text="Buy Now" /></td>
</tr>
</table>
<br />
</ItemTemplate>
</asp:DataList>
<asp:SqlDataSource ID="dlItemsDataSource" runat="server" CancelSelectOnNullParameter="False" ConnectionString="<%$ ConnectionStrings:ConnectionString%>" SelectCommand="spREAD_tblItems" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:Parameter Name="pkiItemID" Type="Int32" />
<asp:Parameter DefaultValue="BRACELET" Name="fkiItemTypeShortText" Type="String" />
<asp:Parameter DefaultValue="FORSALE" Name="fkiItemStatusShortText" Type="String" />
<asp:Parameter DefaultValue="True" Name="bPublic" Type="Boolean" />
<asp:Parameter Name="bSale" Type="Boolean" />
<asp:Parameter Name="mPrice" Type="Decimal" />
</SelectParameters>
</asp:SqlDataSource>
</div>
<asp:Panel ID="pnlLargeImage" runat="server" Width="50%">
<asp:Panel ID="pnlHeader" runat="server" Style="cursor: move;background-color:#DDDDDD;border:solid 1px Gray;color:Black" HorizontalAlign="Center" Width="100%">
<div>
<p>Larger view of item</p>
</div>
</asp:Panel>
<div>
<asp:Label ID="Label1" runat="server"></asp:Label>
<asp:Image ID="imgLargeImage" runat="server" Width="200px" />
<p style="text-align: center;">
<asp:Button ID="OkButton" runat="server" Text="OK" />
</p>
</div>
</asp:Panel>
</asp:Content>

This currently will load the ModalPopup and give Label1 the value of the pkiItemID, so i am successfully getting the item ID and passing it to the ModalPopup.

The problem is that the ImageURL is not being set. Oddly the SetLargeImagePath() method does not appear to run (breakpoints are ignored), although the Label1 value is being set??

Does anyone have any ideas how to get the image to appear in the ModalPopup?

Many thanks

Hi Assimalyst,

Assimalyst:

<script runat="server">
[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod]
public void SetLargeImagePath(int contextKey)
{
imgLargeImage.ImageUrl = "~/Images/Items/" + contextKey.ToString() + ".jpg";
}
</script>

Please contextKey should be a string type. For example, public void SetLargeImagePath(string contextKey){};

We suggest that you should use a debugging tool such as Web Development Helper or Fildder etc.

Assimalyst:

I want to be able to click the image and get a modal popup which displays a large view of the image.

Here is a sample which implement on the client side.

<%@. Page Language="C#" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><script runat="server"></script><html xmlns="http://www.w3.org/1999/xhtml" ><head runat="server"> <title>Change Picture</title> <style> .modalBackground { background-color:Gray; filter:alpha(opacity=70); opacity:0.7; } .modalPopup { background-color:#FFD9D5; border-width:3px; border-style:solid; border-color:Gray; padding:3px; width:250px; } </style></head><body> <form id="form1" runat="server"> <div> <asp:ScriptManager ID="ScriptManager1" runat="server"> </asp:ScriptManager><asp:Image ID="Image1" runat="server" ImageUrl="~/pic/upg_Business.jpg" imgUrl="../pic/upg_HomePremium.jpg" onclick="changePicture(event.srcElement.imgUrl)"/><asp:Image ID="Image2" runat="server" ImageUrl="~/pic/upg_HomeBasic.jpg" imgUrl="../pic/upg_Ultimate.jpg" onclick="changePicture(event.srcElement.imgUrl)"/> <asp:Panel ID="Panel1" runat="server" CssClass="modalPopup" Height="200px" Width="300px" style="display:none"> <asp:Image ID="Image3" runat="server" ImageUrl="~/pic/AJAX.gif"/> <asp:Button ID="Button2" runat="server" Text="Cancel" /> </asp:Panel> <ajaxToolkit:ModalPopupExtender ID="ModalPopupExtender1" runat="server" TargetControlID="Button1" PopupControlID="Panel1" CancelControlID="Button2"> </ajaxToolkit:ModalPopupExtender> <div style="display:none"> <asp:Button ID="Button1" runat="server" Text="Button" /> </div> <script type="text/javascript" language="javascript"> function changePicture(imgUrl){ $get("<%=Image3.ClientID%>").src = imgUrl; $get("<%=Button1.ClientID%>").click(); } </script> </div> </form></body></html>

I hope this help.

Best regards,

Jonathan

programatically updating a panel using onblur

Ok, this is driving me nuts and I can't believe there's not a way to do this.

Basically I have a user control that dynamically adds text boxes to its control tree at runtime. I have an UpdatePanel control sitting in the top of my user control with a button and a literal control. When the button is clicked it calls a buttonclicked method in the user control that sets the literal to some text and calls the update method on the panel. It all does what it's supposed to do when I click the button and AJAX works just fine.

Now here's the problem, how on Earth do I add an onblur event to the dynamically created text boxes that will either

a) update the panel; or

b) call the buttonclicked method directly; or

c) click the button

I've tried

1txtBox.Attributes.Add("onblur","javascript:__doPostBack('ctl00_contentPlaceHolder_quoteControl_quoteButton','OnClick','');");

And a large number of variations on the above but to no avail. The problem with the above is that I don't necessarily know the full id of the button control at compile time (and even if I did I really, REALLY wouldn't want to hard code it in my class) and if it doesn't find the control then it does a full form postback making the update panel redundant. I understand that I cannot wire in a custom event handler directly to the onblur method (like you can for the text changed) so it has to be client side.

Is there a way to trigger server side events through client side script? I have to get this done even if it involves hand rolling some javascript function that I can call from the onblur attribute to call the event.

I'm a back end business tier coder so any help with the client side would be most gratefully appreciated.

Rick Edwards

Ok, I've discovered a nasty way to do this using the event hi-jacking technique or "hidden button" method found here:

http://www.dotnetjohn.com/articles.aspx?articleid=224

I'd originally shy'd away from this as it's blatantly a hack but having now spent two day researching this I can't find another way of doing it.

Basically I add a hidden button to my update panel on the parent control and wire in the button click method on the parent control code behind. I then raise the event handler in the parent user control and pass this to the child control classes that are part of my control factory. When a textbox control is manufactured by the factory I can then add the oblur attribute and wire in the button click event handler. The button click method is initialised in the parent user control and within it I call the update method for the AJAX panel.

This is great for just updating a single panel from multiple onblur events, the problem now occurs if I want to update different panels from different textbox controls, I suddenly have to start adding hidden buttons all over the place so this is far from an ideal answer.

I've just found an article on asynchronous callback features in .NET2 and it looks like I might be able to roll my own textbox control with an onblur method built in, anyone with any experience of this?

Rick Edwards


Sorry if I'm missing something, but why couldn't you just set AutoPostBack="true" on the TextBox?

Firstly the autopostback event is fired on either tabbing out of the textbox or on pressing enter and not necessarily on loss of focus. Also I don't want to fire a postback event, I actually need to fire a custom event that calls the update method on my update panel and therefore run an asynchronous postback and a partial render. I don't want to rerender the entire form.

Hope that makes sense. I tried the autopostback initially thinking along your lines but it couldn't do what I wanted.

Rick Edwards


Yes, you would be limited to whenever AutoPostBack actually fires. But then it will do an async postback (as long as it's in your UpdatePanel or set as a trigger) and run whatever handler you've set in OnTextChanged. It shouldn't reload the entire page.

If AutoPostBack doesn't do what you want, your hidden button method should work, but I'd use MyButton.ClientID to get the ID so you don't have to hardcode it (which as you said is error-prone).

Programmatic Animations

We've got a new app where we are using the Accordian control like the blade interface on XBOX Live and we're building the Accordian control, and adding an updatepanel and adding a UpdatePanelAnimationExtender all programatically from a XML config document. However, I'm not sure how I can add a FadeEffect (http://ajax.asp.net/ajaxtoolkit/Walkthrough/AnimationReference.aspx#FadeAnimation). Here's thw code snippet.

Sean

AjaxControlToolkit.

AccordionPane pane =new AjaxControlToolkit.AccordionPane();

pane.ID = node.Attributes[

"Id"].Value;Label lblHeader =newLabel();

lblHeader.Text = node.Attributes[

"Header"].Value;

pane.HeaderContainer.Controls.Add(lblHeader);

pane.HeaderCssClass = node.Attributes[

"HeaderCss"].Value;

pane.ContentCssClass = node.Attributes[

"ContentCss"].Value;

UpdatePanel updater =newUpdatePanel();

updater.ID =

"updater" + node.Attributes["Id"].Value;

updater.UpdateMode =

UpdatePanelUpdateMode.Conditional;

pane.ContentContainer.Controls.Add(updater);

ProphitAccordion.Panes.Add(pane);

//Since the updater panel is created programatically we'll create our animation for the//updater panels also. Sean

AjaxControlToolkit.

UpdatePanelAnimationExtender upAnima =new AjaxControlToolkit.UpdatePanelAnimationExtender();

upAnima.ID =

"upda" + node.Attributes["Id"].Value;

upAnima.TargetControlID = updater.ID;

AjaxControlToolkit.

Animation updaAnimation =new AjaxControlToolkit.Animation();

updaAnimation.Properties.Add(

"id", ("updaAnimation" + updater.ID));//The following line doesn't work

AjaxControlToolkit.

Animation.FadeEffect upAnFade =new AjaxControlToolkit.Animation.FadeEffect();Hi Sean,

Check outthis post for details on how to dynamically create animations on the server side.

Thanks,
Ted

I know I am a little late to teh party (story of my life), but the link about doesn't work anymore and I am in desperate need of creating animations server side. Different colours for different actions, dynamically created update panels etc. This is about the only subject I can't find any info on, except this one solitary post - and now that's dead.

programmatically add calendarextender

hey all,

is this possible to attach a calendarextender control to a textbox? i'm trying to build all my controls dynamically and i'm having problems with postback/async callback behavior. Mainly not understanding what's going on? anyone have any good references on how to do this? That is, build all controls dynamically with some ajax mixed in?

thanks,

rodchar

rodchar:

is this possible to attach a calendarextender control to a textbox? i'm trying to build all my controls dynamically and i'm having problems with postback/async callback behavior. Mainly not understanding what's going on? anyone have any good references on how to do this? That is, build all controls dynamically with some ajax mixed in?

You certainly can do that.

You will just have to create an instance of the calendarextender, assign it the textbox id to its targetcontrolID property. Also make sure this web page/user control has reference to the AJAX tool kit assembly

e.g.

//first add textbox dynamically and give it an IDTextBox myTextBox =new TextBox();myTextBox.ID ="txtCalendar";//now add the calendarExtendar and assign the targetcontrol IDAjaxControlToolkit.CalendarExtender myCalExt =new AjaxControlToolkit.CalendarExtender();myCalExt.TargetControlID = myTextBox.ID;//add both controls to the form/panel control collectionthis.Form1.Controls.Add(myTextBox);this.Form1.Controls.Add(myCalExt);
/

Programmatically adding ASP.net User Control to UpdatePanel

Hi All, I got a real doozy here. I have read hundreds upon hundreds of forum posts and found numerous others who have replicated this problem, but have yet to find a solution. Through testing I have been able to find the cause of the problem, and will describe it here first textually and then through a code example.

The purpose of what I am trying to do is to create a postback-free web application through the use of ASP.net AJAX UpdatePanels and User Controls. When programmatically adding a User Control to a web page through a normal postback everything works fine. All the controls within the user control are registered properly in the page and any update panels included in the user control also work properly. HOWEVER, if instead of using a full postback you use an UpdatePanel and a partial page update of the UpdatePanel the controls do not get registered with the page and events from them do not fire (for instance, a button click event never hits the event breakpoint).

Because the very same user control works fine if loaded in a full postback or dynamically added from a namespace works fine, I can be relatively sure that it only is trouble when loading via a partial page update into an UpdatePanel. I load the control via the LoadConrol method and then add it to the page via a PlaceHolder control. Theoretically, adding the User Control to the PlaceHolder should register itself and it's controls and events with the page, but it does not.

The following code sample is a UpdatePanel-free page using a user control that works, later I will show the same code with an UpdatePanel that does not.

I think I need to figure out how to register the controls and their events with the page without going through a full page postback. Any suggestions??

This example works as expected:
Default.aspx:

1<%@dotnet.itags.org. Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>23<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
4<html xmlns="http://www.w3.org/1999/xhtml">
5<head runat="server">
6 <title>Untitled Page</title>
7</head>
8<body>
9 <form id="form1" runat="server">
10 <div>
11 <asp:PlaceHolder ID="UCPlaceHolder" runat="server"></asp:PlaceHolder>
12 </div>
13 </form>
14</body>
15</html>

Default.aspx.cs:
1using System;
2using System.Data;
3using System.Configuration;
4using System.Web;
5using System.Web.Security;
6using System.Web.UI;
7using System.Web.UI.WebControls;
8using System.Web.UI.WebControls.WebParts;
9using System.Web.UI.HtmlControls;
1011public partialclass _Default : System.Web.UI.Page
12{
13protected void Page_Load(object sender, EventArgs e)
14 {
15 Control ctl = LoadControl("~/UserControlDemo.ascx");
16 ctl.ID ="UC1";
17this.UCPlaceHolder.Controls.Add(ctl);
18 }
19}

UserControlDemo.ascx:
1<%@dotnet.itags.org. Control Language="C#" AutoEventWireup="true" CodeFile="UserControlDemo.ascx.cs" Inherits="UserControlDemo" %>2<asp:Button ID="Button1" runat="server" Text="Display from UC" OnClick="Button1_Click" /> <br />
3<br />
4<asp:Label ID="Content" runat="server" Text="Content"></asp:Label>

UserControlDemo.ascx.cs:
1using System;
2using System.Data;
3using System.Configuration;
4using System.Collections;
5using System.Web;
6using System.Web.Security;
7using System.Web.UI;
8using System.Web.UI.WebControls;
9using System.Web.UI.WebControls.WebParts;
10using System.Web.UI.HtmlControls;
1112public partialclass UserControlDemo : System.Web.UI.UserControl
13{
14protected void Page_Load(object sender, EventArgs e)
15 {
16 }
17protected void Button1_Click(object sender, EventArgs e)
18 {
19 Content.Text ="Content Changed.";
20 }
21}

Now, consider this variation, where instead of loading the control in the PageLoad event, you do so programmatically via a button Click event. This does not work as it cause a full postback which refreshes the placeholder. Viewstate does not seem to be working in this case. (uses the same user control as the previous example)

Default.aspx:

1<%@dotnet.itags.org. Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>23<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
4<html xmlns="http://www.w3.org/1999/xhtml">
5<head runat="server">
6 <title>Untitled Page</title>
7</head>
8<body>
9 <form id="form1" runat="server">
10 <div>
11 <asp:Button ID="Button1" runat="server" Text="Load User Control" OnClick="Button1_Click" />
12 <br />
13 <br />
14 <asp:PlaceHolder ID="UCPlaceHolder" runat="server"></asp:PlaceHolder>
15 </div>
16 </form>
17</body>
18</html>

Default.aspx.cs:
1using System;
2using System.Data;
3using System.Configuration;
4using System.Web;
5using System.Web.Security;
6using System.Web.UI;
7using System.Web.UI.WebControls;
8using System.Web.UI.WebControls.WebParts;
9using System.Web.UI.HtmlControls;
1011public partialclass _Default : System.Web.UI.Page
12{
13protected void Page_Load(object sender, EventArgs e)
14 {
15 }
16protected void Button1_Click(object sender, EventArgs e)
17 {
18 Control ctl = LoadControl("~/UserControlDemo.ascx");
19 ctl.ID ="UC1";
20this.UCPlaceHolder.Controls.Add(ctl);
21 }
22}

To solve this postback problem, one would naturally want to use an UpdatePanel, like the following example. However this does not work as the controls do not seem to get registered with the page, and further nesting of user controls in UpdatePanels (to create a postback free app) are no better.

Default2.aspx:

1<%@dotnet.itags.org. Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>23<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
45<html xmlns="http://www.w3.org/1999/xhtml" >
6<head runat="server">
7 <title>Untitled Page</title>
8</head>
9<body>
10 <form id="form1" runat="server">
11 <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true"></asp:ScriptManager>
12 <div>
13 <asp:UpdatePanel ID="UpdatePanel2" runat="server">
14 <ContentTemplate>
15 <asp:Button ID="Button1" runat="server" Text="Load User Control into UpdatePanel" OnClick="Button1_Click" />
16 </ContentTemplate>
17 </asp:UpdatePanel>
18 <br />
19 <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
20 <ContentTemplate>
21 <asp:PlaceHolder ID="ContentPlaceHolder" runat="server"></asp:PlaceHolder>
22 </ContentTemplate>
23 <Triggers>
24 <asp:AsyncPostBackTrigger ControlID="Button1" />
25 </Triggers>
26 </asp:UpdatePanel>
27 </div>
28 </form>
29</body>
30</html>

Default2.aspx.cs:
1using System;
2using System.Data;
3using System.Configuration;
4using System.Collections;
5using System.Web;
6using System.Web.Security;
7using System.Web.UI;
8using System.Web.UI.WebControls;
9using System.Web.UI.WebControls.WebParts;
10using System.Web.UI.HtmlControls;
1112public partialclass Default2 : System.Web.UI.Page
13{
14protected void Page_Load(object sender, EventArgs e)
15 {
1617 }
18protected void Button1_Click(object sender, EventArgs e)
19 {
20 Control ctl = LoadControl("~/UserControlDemo.ascx");//loads into the page21 ctl.ID ="UC1";
22this.ContentPlaceHolder.Controls.Add(ctl);//adds to page control tree (or at least it should)23 }
24}

I know I can use the "visible" property of my controls to toggle them on and off a page to create a flicker free experience, however, my application is a database intensive app and I don't want the page running queries against the database unless I'm absolutely sure the user wants them. Rendering a 10 forms and keeping them hidden isn't a big deal, but running 10 queries that the user never wants to see is, otherwise I'd stick to that method, its works perfectly. Any suggestions? Or requests for clarification? Any help you can provide is much appreciated...thanks, Chris.

Chris, are you still working on this?

I've managed to get partial postbacks to fire events on the server from a button on a UserControl that was loaded as a result of a partial postback by an updatepanel.

Here's the code:

protected override void OnPreInit(EventArgs e){base.OnPreInit(e);if (this.Page.Request.Form["__UCTL"] !=null)this.ChangeControls(this.Page.Request.Form["__UCTL"].ToString(),null);elsethis.ChangeControls("Login","Login");}public void ChangeControls(String controlName, String controlTitle){ScriptManager.RegisterHiddenField(this,"__UCTL", controlName);this.host.ContentTemplateContainer.Controls.Clear();UserControl ctl = (UserControl)Page.LoadControl(CONTROL_DIRECTORY +"\\" + controlName +".ascx");ctl.ID = controlName;this.host.ContentTemplateContainer.Controls.Add(ctl);if (controlTitle !=null)this.host.Page.Title = controlTitle;}

I also created an Interface that has a method of ChangeControls with that signature and had my Page implement it so that my UserControls could get access to the method.


Hi Jason,

I figured out how to do it properly, you need to raise an event from the control and listen for it with the page or another control. The code to do so is also simpler than what you have. Check out this thread for more details: http://forums.asp.net/t/1123449.aspx

Feel free to msg me questions if you are confused.

-Chris

Programmatically adding ASP.net User Control to Partial Page Update / UpdatePanel

Hi All, I got a real doozy here. I have read hundreds upon hundreds offorum posts and found numerous others who have replicated this problem,but have yet to find a solution. Through testing I have been able tofind the cause of the problem, and will describe it here firsttextually and then through a code example.

Thepurpose of what I am trying to do is to create a postback-free webapplication through the use of ASP.net AJAX UpdatePanels and UserControls. When programmatically adding a User Control to a web pagethrough a normal postback everything works fine. All the controlswithin the user control are registered properly in the page and anyupdate panels included in the user control also work properly. HOWEVER,if instead of using a full postback you use an UpdatePanel and apartial page update of the UpdatePanel the controls do not getregistered with the page and events from them do not fire (forinstance, a button click event never hits the event breakpoint).

Becausethe very same user control works fine if loaded in a full postback ordynamically added from a namespace works fine, I can be relatively surethat it only is trouble when loading via a partial page update into anUpdatePanel. I load the control via the LoadConrol method and then addit to the page via a PlaceHolder control. Theoretically, adding theUser Control to the PlaceHolder should register itself and it'scontrols and events with the page, but it does not.

Thefollowing code sample is a UpdatePanel-free page using a user controlthat works, later I will show the same code with an UpdatePanel thatdoes not.

I think I need to figure out how to register thecontrols and their events with the page without going through a fullpage postback. Any suggestions??

This example works as expected:
Default.aspx:

1<%@dotnet.itags.org. Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
2
3<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
4<html xmlns="http://www.w3.org/1999/xhtml">
5<head runat="server">
6 <title>Untitled Page</title>
7</head>
8<body>
9 <form id="form1" runat="server">
10 <div>
11 <asp:PlaceHolder ID="UCPlaceHolder" runat="server"></asp:PlaceHolder>
12 </div>
13 </form>
14</body>
15</html>

Default.aspx.cs:
1using System;
2using System.Data;
3using System.Configuration;
4using System.Web;
5using System.Web.Security;
6using System.Web.UI;
7using System.Web.UI.WebControls;
8using System.Web.UI.WebControls.WebParts;
9using System.Web.UI.HtmlControls;
10
11public partialclass _Default : System.Web.UI.Page
12{
13protected void Page_Load(object sender, EventArgs e)
14 {
15 Control ctl = LoadControl("~/UserControlDemo.ascx");
16 ctl.ID ="UC1";
17this.UCPlaceHolder.Controls.Add(ctl);
18 }
19}

UserControlDemo.ascx:
1<%@dotnet.itags.org. Control Language="C#" AutoEventWireup="true" CodeFile="UserControlDemo.ascx.cs" Inherits="UserControlDemo" %>
2<asp:Button ID="Button1" runat="server" Text="Display from UC" OnClick="Button1_Click" /> <br />
3<br />
4<asp:Label ID="Content" runat="server" Text="Content"></asp:Label>

UserControlDemo.ascx.cs:
1using System;
2using System.Data;
3using System.Configuration;
4using System.Collections;
5using System.Web;
6using System.Web.Security;
7using System.Web.UI;
8using System.Web.UI.WebControls;
9using System.Web.UI.WebControls.WebParts;
10using System.Web.UI.HtmlControls;
11
12public partialclass UserControlDemo : System.Web.UI.UserControl
13{
14protected void Page_Load(object sender, EventArgs e)
15 {
16 }
17protected void Button1_Click(object sender, EventArgs e)
18 {
19 Content.Text ="Content Changed.";
20 }
21}

Now,consider this variation, where instead of loading the control in thePageLoad event, you do so programmatically via a button Click event.This does not work as it cause a full postback which refreshes theplaceholder. Viewstate does not seem to be working in this case. (usesthe same user control as the previous example)

Default.aspx:

1<%@dotnet.itags.org. Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
2
3<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
4<html xmlns="http://www.w3.org/1999/xhtml">
5<head runat="server">
6 <title>Untitled Page</title>
7</head>
8<body>
9 <form id="form1" runat="server">
10 <div>
11 <asp:Button ID="Button1" runat="server" Text="Load User Control" OnClick="Button1_Click" />
12 <br />
13 <br />
14 <asp:PlaceHolder ID="UCPlaceHolder" runat="server"></asp:PlaceHolder>
15 </div>
16 </form>
17</body>
18</html>

Default.aspx.cs:
1using System;
2using System.Data;
3using System.Configuration;
4using System.Web;
5using System.Web.Security;
6using System.Web.UI;
7using System.Web.UI.WebControls;
8using System.Web.UI.WebControls.WebParts;
9using System.Web.UI.HtmlControls;
10
11public partialclass _Default : System.Web.UI.Page
12{
13protected void Page_Load(object sender, EventArgs e)
14 {
15 }
16protected void Button1_Click(object sender, EventArgs e)
17 {
18 Control ctl = LoadControl("~/UserControlDemo.ascx");
19 ctl.ID ="UC1";
20this.UCPlaceHolder.Controls.Add(ctl);
21 }
22}

Tosolve this postback problem, one would naturally want to use anUpdatePanel, like the following example. However this does not work asthe controls do not seem to get registered with the page, and furthernesting of user controls in UpdatePanels (to create a postback freeapp) are no better.

Default2.aspx:

1<%@dotnet.itags.org. Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
2
3<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
4
5<html xmlns="http://www.w3.org/1999/xhtml" >
6<head runat="server">
7 <title>Untitled Page</title>
8</head>
9<body>
10 <form id="form1" runat="server">
11 <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true"></asp:ScriptManager>
12 <div>
13 <asp:UpdatePanel ID="UpdatePanel2" runat="server">
14 <ContentTemplate>
15 <asp:Button ID="Button1" runat="server" Text="Load User Control into UpdatePanel" OnClick="Button1_Click" />
16 </ContentTemplate>
17 </asp:UpdatePanel>
18 <br />
19 <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
20 <ContentTemplate>
21 <asp:PlaceHolder ID="ContentPlaceHolder" runat="server"></asp:PlaceHolder>
22 </ContentTemplate>
23 <Triggers>
24 <asp:AsyncPostBackTrigger ControlID="Button1" />
25 </Triggers>
26 </asp:UpdatePanel>
27 </div>
28 </form>
29</body>
30</html>

Default2.aspx.cs:
1using System;
2using System.Data;
3using System.Configuration;
4using System.Collections;
5using System.Web;
6using System.Web.Security;
7using System.Web.UI;
8using System.Web.UI.WebControls;
9using System.Web.UI.WebControls.WebParts;
10using System.Web.UI.HtmlControls;
11
12public partialclass Default2 : System.Web.UI.Page
13{
14protected void Page_Load(object sender, EventArgs e)
15 {
16
17 }
18protected void Button1_Click(object sender, EventArgs e)
19 {
20 Control ctl = LoadControl("~/UserControlDemo.ascx");//loads into the page
21 ctl.ID ="UC1";
22this.ContentPlaceHolder.Controls.Add(ctl);//adds to page control tree (or at least it should)
23 }
24}

I knowI can use the "visible" property of my controls to toggle them on andoff a page to create a flicker free experience, however, my applicationis a database intensive app and I don't want the page running queriesagainst the database unless I'm absolutely sure the user wants them.Rendering a 10 forms and keeping them hidden isn't a big deal, butrunning 10 queries that the user never wants to see is, otherwise I'dstick to that method, its works perfectly. Any suggestions? Or requestsfor clarification? Any help you can provide is muchappreciated...thanks, Chris.

My suggestion is to not use an updatepanel for this. Google for ScottGu's blog on templating tricks; you can use a service to grab an ascx, feed it a datasource to populate the data then send the results to the page. use javascript to insert those results into the page DOM where needed, and code all your functionality in js or web methods of one form or another. It's a much cleaner / lower overhead way to do what you're trying to do anyway.


Hi Paul, I took a look at ScottGu blog, I believe this is the article you were referencing: http://weblogs.asp.net/scottgu/archive/2006/10/22/Tip_2F00_Trick_3A00_-Cool-UI-Templating-Technique-to-use-with-ASP.NET-AJAX-for-non_2D00_UpdatePanel-scenarios.aspx

Unfortunately this is not the solution I am looking for. By using this method I lose the main benefits of ASP.net: managed code, event based triggers, and the rest of the integrated features. I believe this method will cause the same problem, whatever I load into the page, the page won't be aware of it and no events will fire.

For now I am going to have to use postbacks, and I'll used the update panels for keeping things like sorting gridviews postback-less.

Thanks for the suggestion though!


I am having exactly the same problem

Can someone please help?

In similar situations before, I have used javascript and other hacks, but I feel reluctant to try to do it again. If we have a framework that can be used and can make work simpler, then It makes sense.

However, these kind of problems are frustrating, and I don't know what is the resolution. I am sure people mus thave encountered this before.

Can someone help?


This is more a dynamic controls problem than an AJAX problem.

When you dynamically add a control, you have to add it EVERY request. By moving it from PageLoad to Button_Click, you've stopped creating the control every request. You only create it if the button is pressed. That is why the events won't fire when you use controls within the user control -- because on the postback, the control doesn't even exist! The postback data is for a control that isn't in the control tree, because you didn't add it, because the event that adds it isn't firing again.

The technique to solve this is to utilize viewstate to remember that the control has been added, so that you can add it from the LoadViewState method. In your click handler, call a new method - LoadUserControl(). Define LoadUserControl to create and add the control, and to set a viewstate key, ViewState["LoadUserControl"] = true. Then override LoadViewState, and after calling base.LoadViewState, look for that viewstate key. If its true, call LoadUserControl().

New problem... Now its possible it will be added twice -- if you click the same button a 2nd time, LoadViewState will call it, and so will your button click handler. So add code to your button click handler to avoid creating it if its already loaded -- just check for the viewstate key.


Infinities...This is very interesting, thank you for your response! Unfortunately you lose me when you talk about overriding the LoadViewState. How would you modify the following code to accomplish what you are saying?

protected void Button_Click(object sender, EventArgs e)
{
Control ctl = LoadControl("~/userControl.ascx");
this.Panel1.Controls.Add(ctl);
}
Thanks!

Ok, that sounds promising. But, I don't think the situation would work still.

I have a gridView. In every row of a gridview, one of the cells contains a nested update panel. When the user clicks on a particular row, a user control dynamically gets added to the nested update panel. This works fine.

When I click on a particular button INSIDE this user control then the postback disappears, no events are triggered and nothing happens. The fact that the control probably does not exist makes sense because it justifies what happens, as in no events are fired.

However now this user control has values and data inside it, so when you are saying to load that control again, what happens to the value and the data, it looks like that data is lost. Is that not right?

Basically, in my situation AJAX cannot help. In the first place my user control should already have a viewstate in order to persist the value of data and state of the elements inside the user control. Since its viewstate is not stored, the "re-adding" will simply not work at all.


gsinha25:

However now this user control has values and data inside it, so when you are saying to load that control again, what happens to the value and the data, it looks like that data is lost. Is that not right?

No that is not right. The fact you are loading it again doesn't mean its data is lost. All controls are reloaded every request, even the statically declared ones. ViewState maintains itself through the framework, but it only maintains the data in the control, not the control itself.

gsinha25:

Basically, in my situation AJAX cannot help.

You would have the same problem if you were not using ajax. What you'd see is that the loaded user control would disappear after you click a button in it.

gsinha25:

In the first place my user control should already have a viewstate in order to persist the value of data and state of the elements inside the user control. Since its viewstate is not stored, the "re-adding" will simply not work at all.

ViewState is maintained for the control. All you have to do is make sure it exists every request. It will work, trust me.


I'm sure the formatting of this is going to be off, but here's the basic idea.

protected void Button_Click(object sender, EventArgs e)
{
LoadUserControl();
}
private void LoadUserControl()
{
Control ctl = LoadControl("~/userControl.ascx");
this.Panel1.Controls.Clear();
this.Panel1.Controls.Add(ctl);

 ViewState["Loaded"] = true;

}
protected override void LoadViewState(object savedState)
{
base.LoadViewState(savedState);

 if (ViewState["Loaded"] != null)
LoadUserControl();
 }


Hi Infinities,

This is starting to make sense. I believe what you are talking about will work for my problem - in fact I often assumed it had something to do with the viewstate, however my knowledge and experience with it is limited. (I am new to C# and ASP.net, coming over from ColdFusion.) I am still a little confused on the the LoadViewState override. As I understand it, this event fires after the Init event in the lifecyle, and it's goal is to reload the user control if it has been added to the page. One question that pops up here, and may be what gsinha was referencing, does chages to the control also progress if it is reloading the control every time? For instance, if the user control is a gridview populated from a database and I have sorted and/or filtered it, would these sorts and filters be passed along as well?

Another question, when you assign the view state key in "ViewState[" "] = true" does it matter which key you use? And a final question, where is the savedState object coming from in the LoadViewState override?

Thanks again for your help!

P.S. I read your writeup at your website on the viewstate, I think i'll need to read it three or four more times before I can make sense of it all but amazing stuff, I love the attention to detail!


ChrisCicc:

As I understand it, this event fires after the Init event in the lifecyle, and it's goal is to reload the user control if it has been added to the page.

The general role of LoadViewState is to deserialize the control's share of the page's entire viewstate payload. Think of viewstate as just a bunch of data -- data which is associated with each control on the page. On a postback, that data is available to the control that owns it again, if it's still around that is. The role of the code I gave you is to recreate the control if it was remembered previously that it had been created.

ChrisCicc:

One question that pops up here, and may be what gsinha was referencing, does chages to the control also progress if it is reloading the control every time? For instance, if the user control is a gridview populated from a database and I have sorted and/or filtered it, would these sorts and filters be passed along as well?

Yes -- because what you have to understand is that all controls are reloaded every request. In fact, the page is completely reconstructed from the ground up every request. Remember request/response mechanism of the web is essentially a stateless process. ASP.NET and other frameworks create the feeling of statefulness through tricks like ViewState and Session state. ViewState is persisted across posts -- the controls are not. You create the control tree for the page by either statically declaring it with asp.net markup, or by dynamically creating the controls yourself. But either way, the controls start completely fresh and new every request. ViewState is then deserialized and injected into the controls, restoring them to the state they were on the last request.

ChrisCicc:

Another question, when you assign the view state key in "ViewState[" "] = true" does it matter which key you use?

No -- the idea is just to remember the fact that the control was loaded. Each control's viewstate is scoped to it, so there's no risk of using a key thats already in use by some other control.

ChrisCicc:

And a final question, where is the savedState object coming from in the LoadViewState override?

That is the deserialized viewstate associated with that specific control. The base implementation uses it to repopulate the keys stored in the ViewState statebag.


ChrisCicc:

P.S. I read your writeup at your website on the viewstate, I think i'll need to read it three or four more times before I can make sense of it all but amazing stuff, I love the attention to detail!

Thanks for reading :) I know it's quite long... but hopefully worth it.


It works!! Thanks a bundle! This solved the most important problem I had, which was loading the user control on to the page via an Update Panel. It does however bring up a few further questions that I was hoping you could help with!

First, how do I modify your code so that I can have multiple buttons load different UCs each while still using the LoadViewState override? The following code is my best attempt at it:

Instead of using the click event to call the LoadUserControl function, I did this:

  
protected void LinkButton_Click(object sender, EventArgs e)
{
MainBodyPanel.Controls.Clear();
Control ctl = LoadControl("UserControl.ascx");
MainBodyPanel.Controls.Add(ctl);

ViewState["Loaded"] =true;
}

And then in the override I did as you suggested, only added an addtional If statement for each button and control,
and sent it back to the click event function instead of the LoadUserControl so that each control could have its
own viewstate key.
While I can add new controls to the page, I cannot see them again once another control calls the .clear()
function an all that is left is the viewstate which then throws an error as it doesn't see the same control tree.
Is there a better way?
 
The second problem I have is I cannot get different user controls to communicate with each other. This is
apparent in two places. The first is I have a user control with a set of links. it is these links that call the
other user controls into the update panel dynamically. If I add the UserControl dynamically before the page
loads, the links can't see the container panel on the page. I tried using this.findControl("...").Controls.Add()
but that didn't work. So for now I have the links hard coded into the page instead being their own user control,
but it's really too complex to keep doing it that way, and it limits my nesting options.
Thanks again for any help u can provide! 
 

Ok... help me understand :) You have a bunch of links, which when one is clicked, you want to dynamically load a user control into a particular spot. Is that 'spot' different for each link? If you click on one link and then another are there supposed to now be 2 controls on the page or does the 2nd one replace the first?

I'll assume you want only 1 control at a time.

What you described sounds like it should work. I personally wouldn't explicitly call the event handler -- thats usually a bad idea. It won't cause any problems if you know what you're doing but its better design to have a 3rd method that they both call, which gives each method a clear distinct purpose (its generally bad if you have to think... who called this method?).

One think you should definitely do is give the User Control you load a particular ID. Make the ID based on something that will (1) be exactly the same every time and (2) be different for different user controls. So for example, clicking on Link1 might load UC1.ascx with ID "uc1", and clicking Link2 might load UC2.ascx with ID "uc2". The reason for this is.. well, when you dont specify an ID, any control that requires one (textboxes for example) will use an autogenerated one. But if you load controls differently on a postback than you did on the first request, the IDs wont necessarily be the same, causing problems. Assigning an ID avoids that. You shouldn't have been getting the exception you mentioned... try what I said and let me know. If you still get it, show me some code...

About your user control communication problem... I'm not following 100%. Where and when exactly are you calling FindControl, and what control are you trying to find? With controls whenever you find yourself trying to get two of them to talk directly to each other... well its usually a sign that you could improve your design a bit. The control should be self sufficient, it shouldn't be broken because something else on the page isnt just so. Rather than have the control talk to the other control, you can have it raise an event. The page then listens for the event and decides what to do with it (something which the original control doesn't much care about), which may be to push something into another control on the page (the origin of which that control doesn't much care about). Much less coupled that way.


"I'll assume you want only 1 control at a time." correct assumption. there is a panel placeholder that the controls get swapped in and out of.

I tried adding the ID as you suggested but the exception still came up. Here is the code as it currently stands:

1protected void ViewCustomerListLinkButton_Click(object sender, EventArgs e)2 {3 MainBodyPanel.Controls.Clear();4 Control ctl = LoadControl("~/UserControls/CustomersControls/CustomerList.ascx");5 ctl.ID ="CustList";6 MainBodyPanel.Controls.Add(ctl);78 ViewState["CustList"] =true;9 }1011protected void AddCustomerLinkButton_Click(object sender, EventArgs e)12 {13 MainBodyPanel.Controls.Clear();14 Control ctl = LoadControl("~/UserControls/CustomersControls/CustomerAdd.ascx");15 ctl.ID ="CustAdd";16 MainBodyPanel.Controls.Add(ctl);1718 ViewState["CustAdd"] =true;19 }2021protected override void LoadViewState(object savedState)22 {23base.LoadViewState(savedState);2425if (ViewState["CustList"] !=null)26 ViewCustomerListLinkButton_Click(null,null);2728if (ViewState["CustAdd"] !=null)29 ViewCustomerListLinkButton_Click(null,null);3031 }

The exception is thrown because when I click on a second link, it Clears the MainBodyPanel control list, and the viewstate is looking for the control list that includes the now removed control. I tried various ways I could think of to remove the viewstate but to no avail...

"What you described sounds like it should work. I personally wouldn'texplicitly call the event handler -- thats usually a bad idea. It won'tcause any problems if you know what you're doing but its better designto have a 3rd method that they both call, which gives each method aclear distinct purpose (its generally bad if you have to think... whocalled this method?)."

I couldn't figure out a way to do this. I was having each click event pass the url via the function call LoadUserControl("~/control.ascx") but I couldn't figure out how to have the loadviewstate override pass the url back when needed, so I did it as you see above.

About the communication problem, in more detail, the problem is actually with the code above. Right now that is in my pages code behind, if i make those links into a user control, and then add the control to the page with those functions in the controls code behind, it cannot see the container panel (which in this case is the MainBodyPanel). I tried using the find control method but it still couldn't see it. With the links and event handlers hard coded it works fine.

Thanks!


With this code, once you click on one of the buttons, that control will always be loaded. When you click on one button you need to 'clear' the viewstate key of the other, otherwise you'll be trying to load both controls all the time. Pretty sure that is why you are getting the error, too. Easier if you just use the same key with a different value.

About the event handler thing...

protected void Link1_Handler(object sender, EventArgs args) { Foo(); }
private void Foo() { /* load Foo, set ViewState["Loaded"] = 1 */ };

protected void Link2_Handler(object sender, EventArgs args) { Bar(); }
private void Bar() { /* load Bar, set ViewState["Loaded"] = 2 */ };

protected override void LoadViewState(object savedState) {
base.LoadViewState(savedState);

if(ViewState["Loaded"] == 1) {
Foo();
}
else if(ViewState["Loaded"] == 2) {
Bar();
}
}

You might be tempted to store the path to the actual UserControl in ViewState, that way you can just LoadControl(ViewState["Loaded"]) ... but, don't :) Treat ViewState like user input. Don't trust it. If you did it that way, the user could maniuplate viewstate in such a way that they could cause any user control in your site to load, rather than be restricted to the two you want.

Ok... so I'm still confused about your links problem. You have each link as a user control, and when clicked you want them to load their content into the parent? Controls should not modify their parent's controls. It would be better like I said, to have an event raised by the control. The page, which contains all these link controls, just hooks that event on each control and then loads the control into the appropriate place. Your FindControl probably isn't working because FindControl only finds controls within the current naming container. User controls are naming containers. So when you say, this.FindControl("foo") from within a UserControl, you're only looking for a control named "foo" WITHIN the user control, not higher. To go higher you have to call FindControl on a control thats higher. But you still have to be careful with naming containers. You could start at the page level with this.Page.FindControl("foo"), but that will only find controls named "foo" that are children of page or children of non-naming containers in page. Imagine if you had a user control that contained control with ID "foo", and then you put 5 of them on the page. Which would you expect Page.FindControl("foo") to find? Its ambiguous -- thats why it won't find ANY. Each Foo is within a naming container, so their actual IDs are "uc1$foo", "uc2$foo", etc (where uc1=id of user control 1). If you know for sure the control will be in a particular place (for you it sounds like in a master page), then go ahead and hard code that ID... but be warned, its a fragile way to do it. Another approach is to have your Page expose a "MasterContainer" property of type Control. The user controls can then just say ((MyPageType)this.Page).MasterContainer.Controls.Add(), and it will work so long as the control is on a page that inherits from "MyPage" (which, all of your pages could inherit from).Ad infinitum... lots of different ways to deal with it.

programmatically created buttons click event handler not working in updatepanel

i have a hovermenuextender with Target Control - an updatepanel, PopupControl - a panel with button named edit.

when i press edit, a textbox, and a button are created programmatically and placed inside the updatepanel.

the button's click event has a handler (added programmatically) which shud replace the text in updatepanel with the text in textbox, but this is not working - here's the snippet:

1protected void OrseButton_Click(object sender, EventArgs e)2 {3 OrseUpdatePanel.ContentTemplateContainer.Controls.Add(tbox);4 OrseUpdatePanel.ContentTemplateContainer.Controls.Add(savebtn);5 savebtn.Text ="Save";6 savebtn.Click +=new EventHandler(savebtn_Click);7 }89void savebtn_Click(object sender, EventArgs e)10 {11string temp;12 temp = tbox.Text;13 OrseUpdatePanel.ContentTemplateContainer.Controls.Clear();14 OrseUpdatePanel.ContentTemplateContainer.Controls.Add(new LiteralControl(temp));1516//throw new Exception("The method or operation is not implemented.");17 }

help me on this...i m using vs 2005, asp with ajax, c#

whats hapening is ur manipulating ur button and events at runtime, so when the page postback, the buton info and event is lost, what u need to to is save the whole thing to a viewstate, then on page call back u must recall this viewstate and reassign it to the button.

savebtn.Text ="Save";
savebtn.Click +=new EventHandler(savebtn_Click);

ViewsState["btn"] = savebtn;

On ur callback

savebtn = (button)ViewsState["btn"]

Hope this helps


i placed :

savebtn = (button)ViewsState["btn"]

in savebtn_click method.

now when i run it, it gives error serializing value 'system.web.ui.webcontrols.button' of type 'system.web.ui.webcontrols.button'


ok, on each callback recreate the event for ur button, coz when creating event at runtime, and when there'sa postback or callback, the event is lost, so have to recreate it and Once created ASP.Net directly rebind it.


can i have some example code...i wanna make sure i got u completely.

Programmatically creating OpacityBehavior

How can I programmatically create a opacitybehavior and attach it to a control and set its opacity value ?

Following doesnt seem to work in both IE and firefox? I changed the order of initialize() in my following code, it still doesnt work.

function setOpacity()

{

varp_lightgreendiv =new Sys.UI.Control($('lightgreendiv'));

var a =new Sys.UI.OpacityBehavior() ;

a.set_value(0.1) ;

p_lightgreendiv.get_behaviors().add(a) ;

p_lightgreendiv.initialize() ;

a.initialize() ;

}

Thanks

Indo.

Hi,

I've answered to this threadhere.

Thanks it works! I dont know what i am doing wrong in my example.

~Indo.

Programmatically Scroll GridView Control

I have an AJAX enabled web form with several data-filled GridView controls. The users accessing this web app will navigate the site via touch-screen monitors (i.e.: no mouse). As a result, I need an easy way for them to scroll the GridViews when the data is not visible. I want them to click on a button, which will then accordingly scroll the grid up or down. I have tried all the various combinations of the suggestions that I could find:

GridView.Rows(20).RowState = DataControlRowState.Selected

and

GridView.Rows(20).Focus()

and

GridView.SelectedIndex = 20

and

'Set focus to a hidden button control (column)
GridView.SelectedRow.Cells(5).Focus()

If I could set focus to a particular row, I think it should scroll to show that row. This would be fine, but nothing seems to work. Anyone have any suggestions on how I could programatically scroll a GridView control?

Thanks!

Hi AxeRose,

Did you find any solution for this problem?

I have asimilar purpose and meantime I don't have no idea, how to do this.


No, I never found a solution. I ended up using Paging instead -- which works fine for my situation.

Good luck!


I do not know if this works (and probably only in IE or in everything but IESmile ) but there is a javascript function called scrollIntoView that you could try. Just a suggestion.


Seehttp://forums.asp.net/t/1162570.aspx

You can use the JavaScript function: scrollTo(...)

-Damien


<script type="text/javascript">
var prm = Sys.WebForms.PageRequestManager.getInstance();

prm.add_beginRequest(beginRequest);

function beginRequest()
{
prm._scrollPosition = null;
}
</script>

http://forums.asp.net/t/1156877.aspx

Monday, March 26, 2012

Programmically create ModalPopup

I have load data and show it in DataGridView control.
What can I do to archieve the following criteria:

When user click on a specific cell - it will bring up detail records in modalPopup extender control?

See forum posthttp://forums.asp.net/thread/1613190.aspx. It talks about PopupControl but you could use the same principle here.

Proper documentation on new Ajax installation

A new beginner to Ajax may likely find it a bit difficult to install Ajax control toolkit controls on its toolbox and also the autocompelete extender control and e.t.c. in Microsoft.Web.Preview.dll

I found lots of documentation athttp://ajax.asp.net

You can download the controls and see samples of how to use them. Also in my blog I added links to Scott's doc and samples

Proper time to add UpdatePanel trigger

What is the proper time to add a trigger to an UpdatePanel from code-behind?

I currently have a control that acts as a NamingContainer. I am trying to have it register a couple of its buttons as async triggers if it senses that it is a child of an UpdatePanel. This is because these controls are databound (there are multiples of them in one UpdatePanel) so I cannot add the IDs of the controls declaratively.

I tried adding them in the PreRender phase of the control, but when I try it out I get a nasty exception on Render during a postback (below). I can only assume (from reflection) that initially, the triggers are being created when the controls are recreated from ViewState, then the controls those triggers reference get tossed aside when the list databinds after the change, so there's a null reference when the triggers from the first set try to find their real controls. However, I don't have any idea how to avoid this. Any help would be greatly appreciated.

Object reference not set to an instance of an object. 0.273490066474929 0.000559
at System.Web.UI.AsyncPostBackTrigger.HasTriggered()
at System.Web.UI.UpdatePanelTriggerCollection.HasTriggered()
at System.Web.UI.UpdatePanel.get_RequiresUpdate()
at System.Web.UI.PageRequestManager.ProcessUpdatePanels()
at System.Web.UI.PageRequestManager.RenderPageCallback(HtmlTextWriter writer, Control pageControl)
at System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children)
at System.Web.UI.Control.RenderChildren(HtmlTextWriter writer)
at System.Web.UI.Page.Render(HtmlTextWriter writer)
at IDM.Manage.UI.Page.Render(HtmlTextWriter writer) in C:\Projects\IDM.Manage\IDM.Manage\UI\Page.cs:line 39

I had this same problem when trying to add a trigger in the Page_Load.

It worked fine when I moved it to the Page_Init

Proper way of updating the control toolkit

Hi,

When a new version of the control toolkit is released, what are the proper procedures to replace the new downloaded files with the old ones? Unzip and overwrite all the old files? Then reload the toolbox controls in VS.NET? If that's the case will I have to change anything in my application, whereby the "old" controls are still existent?

Upgrading to a newer Toolkit release


If you were using an older release of the Toolkit and now need to move to a later version here are the recommended steps:

Binaries:Overwrite all old instances of the Toolkit binary "AjaxControlToolkit.dll" on your machine with the new one.Toolbox items:Delete the old tab that listed Toolkit controls and recreate it using the new Toolkit DLL.Toolkit templates:Reinstall the new "AjaxControlExtender.vsi" and check to overwrite the old templates in the "Add Templates" wizard.

Property value disappear on click with user control

Hi,

I have a user control which require input text boxes and a caclulate button. When I hit the recalculate button, lblMonth becomes blanks. Please see the code below and guide how to keep the lblMonth the value of lblMonth

============
<asp:UpdatePanel ID="upPanelSales" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Label ID="lblMonth" runat="server" Font-Bold="true" ForeColor="white" CssClass="heading" />
-- some text box controls
<asp:Button ID="btnReCalc" runat="server" Text="Recalc." CommandName="Calculate" CommandArgument="ReCalc" OnCommand="Calculate" />
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnReCalc" EventName="Command" />
</Triggers>
</asp:UpdatePanel
Code Behind
Private _MonthNameAs String

Public Property MonthName()As String
Get
Return _MonthName
End Get
Set(ByVal valueAs String)
_MonthName = value
End Set
End Property

Protected Sub Page_PreRender(ByVal senderAs Object,ByVal eAs System.EventArgs)Handles Me.PreRender
Me.lblMonth.Text = _MonthName
End Sub

Protected Sub Calculate(ByVal senderAs Object,ByVal eAs CommandEventArgs)
If e.CommandName ="Calculate"Then
Select Case e.CommandArgument
Case"ReCalc"
ReCalculate()
End Select
End If
End Sub

Main Page
=========

<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" />
<Sales:Input ID="uc" runat="server" />
Code Behind

Sub Page_Load
uc.MonthName = Month1
End Sub

you probably want to do this in your main page code behind so it only gets set when the page loads the first time

Sub Page_Load

if not Page.IsPostBack Then
uc.MonthName = Month1
end if
End Sub


My main page contains 4 link button controls called Qtr1, Qtr2, Qtr3, Qtr4 and I want to change the month value based on user clicking on quarter links? The real problem is due to submit button inside the user control and partial page refresh has applied on this user control.


so you solved it? or you're still asking?

if those 4 links are outside of the updatepanel they will trigger a full post back and the data inside the update panel contents will be treated no differently than if they weren't inside an updatepanel.

if you click the the linkbutton inside the updatepanel the only thing that will happen is the data within the updatepanel will postback and the associated button event will fire. Only data within the updatepanel will post back to the server though. Data outside of the updatepanel will still appear to the server as the same data regardless of change on the client side...

Property value undefined after succesfull web service call

Hello,

hopefully I can explain my problem.

I started to create extended control with ajax control toolkit. Idea is, that I have textfield which works so

that it suggest values every time when user hits key. Like that --> http://www.google.com/webhp?complete=1&hl=en

Now in SearchTextBoxBehavior.js file I have two propertys, which one hold id for listbox which shows suggestions.
(I think in that google example, the control is span or div element.)


Ok, I have succesfully created event, which is occurred when user hits key in textfield. Webservice call is made in bold code line-->

1_onkeyup : function() {
23 var targetButton = $get(this._TargetButtonID);
4 var targetListBox = $get(this._TargetListBoxID);
5
6if(targetButton && targetListBox) {
7 targetButton.disabled =true;
8
9// unescape() convert′s a string to URL-encoded form10 var searchValue = unescape(this.get_element().value);
11
12if(searchValue !="") {
13// Set suggestion visible14 targetListBox.style.visibility ="visible";
15
16MyCompany.WebServices.MySearch.GetDataTableFromWebservice(searchValue,this._onSucceeded);
17 }
18else {
19// Set suggestion hidden when there is no search value inserted20 targetListBox.style.visibility ="hidden";
21 }
22 }
23
24 },
 
Web service call is succesfull, and returns into function:
 
1_onSucceeded : function(Result) {23var targetListBox = $get(this._TargetListBoxID);45var table = Sys.Preview.Data.DataTable.parseFromJson(Result);67...89}
 
Problem is, that in that _onSucceeded function, propertythis._TargetListBoxID is
undefined. In function, where I made web service call, the property was ok, and I could
make instance about control.
 

Hi,

you need to modify the context under which the callback is executed. This can be done with a delegate and the Function.createDelegate method:

MyCompany.WebServices.MySearch.GetDataTableFromWebservice(searchValue,Function.createDelegate(this, this._onSucceeded));



Hi,

it worked, thanks. :)


Yesterday evening I managed to circulate problem, with solution below.

1var inputParams =new Array();2inputParams[0] =this._TargetListBoxID;3inputParams[1] =this._TargetButtonID;4inputParams[2] =this._ListControlTextField;5inputParams[3] =this._ListControlValueField;67MyCompany.WebServices.MySearch.GetDataTableFromWebservice(searchValue,this._onSucceeded,this._onFailed, inputParams);

Hi,

yes, as your code shows, you're passing a context object as the last parameter to the proxy method. This is useful especially if you want to access only certain references in the callback and not the whole instance.


Hi All,

huygens...is there any way you can post your full code? I'm looking to do something similar with the toolkit. Would be greatly appreciated.

proplem with add ajax control

dir sair

when i add any ajax control in wesite using ajax template i cant using prifix ajaxtoolkit

i must drag and drop the control and his prifix will be cc:

ex: cc1:modelpopupextender

can i know whay?

thank you

here cc1:modelpopupextender means customControl:modelpopupextender

u have to register the AjaxToolKitControl

<%@. Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit" %>

this line apperd on top of head section like Page

then u can drag and drop the control

that time it will generate ajaxToolkit: modelpopupextender

Thank

Kunal


Hi,

Another tip is that you can register it in web.config so that don't have to do it in everypage.

<system.web>
<pages>
<controls>
<add assembly="AjaxControlToolkit" namespace="AjaxControlToolkit"tagPrefix="ajaxToolkit"/>
<add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</controls>
</pages>

Hope this helps.