Wednesday, March 28, 2012

Dynamic HTML ToolTip that loads OnHover/OnMouseOver

right now i have a web app that has a repeater (rather large) with a literal for one of the columns. this literal is a number based on the amount of entries and on load has javascript added to it that displays row specific information built from a database when you hover over it. the problem is that every time the page loads, every tooltip is loaded. i want to only go to the DB and get this info when they hover over that literal. so onmouseover of this literal would trigger an event that builds the tooltip and displays it as before.

i've searched this forum (which by the way isn't efficient) along with some good old Google hunting with no luck. can anyone point me in the right direction? oh yeah, i also would prefer not to use some random 3rd party tool. =)

This is fairly easy. Follow this tutorial:http://ajax.asp.net/docs/tutorials/ConsumingWebServicesWithAJAXTutorial.aspx except that in the 'OnComplete' javascript function that fires when the web service returns, have it fill whatever container you're currently using to display the tooltip (mostly this ends up being the title attribute of one element or another).


I'll check it out and see how it goes. Thanks for the reply =)

dynamic html production to call ajax post via javascript

I am maintaining a page that creates html (not server controls) elements dynamically and when one changes I need to call the ajax postback. Is that possible? The page that is created can't know ahead of time that it will need to post through ajax....

So long as you add a client-side Event handler to your html control when you create it, yes, you can wire it up to make asynchronous requests:http://www.mikesdotnetting.com/Article.aspx?ArticleID=40. Note, the methodology outlined in the article doesn't make an ASP.NET Ajax request or postback. It differs in that it only makes a call to the server-side method you want to invoke. This can be better than using ASP.NET Ajax, in that you aren't recreating all the controls on the page.

Dynamic highlight should be easy! (UpdatePanelAnimationExtender)

Hi,

I have a page fragment which looks roughly like:


<UpdatePanel>
<Repeater>
<Item>
<div id="something-#">item text</div>
</Item>
</Repeater>
</UpdatePanel>


When a new item is added, I want to have the newly added <div> higlight. So far I've manged to get the first item to highlight with an UpdatePanelAnimationExtender:

<ajaxToolkit:UpdatePanelAnimationExtender ID="upae" BehaviorID="Highlight"
runat="server" TargetControlID="UpdatePanel1">
<Animations>
<OnUpdated>
<Sequence>
<Color AnimationTarget="something-1"
Duration=".5" PropertyKey="backgroundColor"
StartValue="#FFFF90" EndValue="#FFFFFF" />
</Sequence>
</OnUpdated>
</Animations>
</ajaxToolkit:UpdatePanelAnimationExtender>

What I can't figure out how to do is get the most recently added item to highlight. It seems like I need to be able to set the "AnimationTarget=" attribute in server code, but after reading posts on here I believe I can't.

Is there any easy way to do this?

Well, to reply to myself, here's how I achieved it. (I'm sure there must be an easier way though).

In my button click event handler I add a data item with the Id of the new object.

if (ScriptManager.IsInAsyncPostBack)
{
System.Web.Script.Serialization.JavaScriptSerializer json =
new System.Web.Script.Serialization.JavaScriptSerializer();

// Return the new CommentId ScriptManager.RegisterDataItem(CommentsUpdatePanel, json.Serialize(comment.CommentId),true);
}

Then in my page, use the EndRequestHandler to pick up the new Id. I then dynamically create some animation code
using the client ID that I've just created.

 function EndRequestHandler(sender, args)
{
var dataItems = args.get_dataItems();
var newCommentId;

if (dataItems[CommentsUpdatePanel] != null)
{
newCommentId = dataItems[CommentsUpdatePanel];
}

 var colorAni = new AjaxControlToolkit.Animation.ColorAnimation(newCommentEl,
2, 30, "style", "backgroundColor", "#FFEF3F", "#FFFFFF");
/// More animation code }
It works, but it seems very clunky to me. 

Hi,

There are a couple of ways you could do this that are a little easier. A better approach would be something like <Color TargetScript="GetLatestDiv()" ... > combined with function GetLatestDiv that does a look up on the ID stored in your data item and returns its element.

Thanks,
Ted

Ted,Thanks for your reply.

I did consider this method, but the problem I faced is getting to the dataItem in the 'GetLatestDiv()' method. The documentation says that:

"If you use the RegisterDataItem method of the ScriptManagercontrol to send extra data during an asynchronous postback, you canaccess that data from the PageLoadingEventArgs, PageLoadedEventArgs,and EndRequestEventArgs objects"

In other words, as far as I can tell, I need to be in the EndRequestHandler method to get at the dataItem. It appears that EndRequestHandler() is called after GetLatestDiv() is evaluated, so I can't even use a shared variable, which would be quite nasty anyway.

Is there any other way I can get at the DataItem?

Hi,

Right - you'll still need your handler to pull the DataItem out. I was thinking you could then store that in a global var that's later read by GetLatestDiv(). Better yet though, you could make it one step simpler and just say TargetScript="_lastDiv" where _lastDiv is a global reference to the element you obtained from your handler.

Thanks,
Ted

Dynamic Gridview

Hi!

I've got a quetion on dynamic gridview load. In my atlas website project i have a gridview that i want to load dynamically. That is, I don't want to load all the data in my datasource because the web page could charge slowly; so, i want to charge only part of the data as fast as possible then, load the other paghes when the user asks for it. How can I do it? Am I to write a C# class in order to manage the load?

Thanks

hi,

it depends on what level do u want to do this ,at what level is it loading slowly.....1)from the dataserver to the dataobject or 2)the control to the current instance of the page...?


it downloads slowly from the dataserver to the dataobject

where is your select query placed?may be in datasource...... place it in a stored procedure as stored procedures are precompiled..... & call the stored procedure....also set EnablePaging to true of the gridview.


My query select is placed in my datasource and my EnablePaging is set to true

Dynamic generated Controls doesnt work, javascript error

I have an ajax enabled control which has a Dropdownlist that changes the Textbox when index gets changed. It is working fine if I use an ASPX page that contains the control in design time.

However, when I dynamically add this control to the ASPX in run time, I got an error when the Dropdownlist is triggered:

Javascript error: System.InvalidOperationException: A control with ID 'myDropDownList' could not be found for the trigger in UpdatePanel..etc..

What should I do? Please help..

There's a good chance that if you look at your page source you'll find that the dynamic control does not have a clientside Id of 'myDropDownList'. It'll probably have something more complex like ct100_myDropDownList or something.

Two possible fixes: 1) wire up your javascript on something other than the id (e.g. iterate over getElementsByTagName), or 2) render the control's ClientID inside a script tag on the page like: var ddl = '<%= myDropDownList.ClientID %>'

HOpe that helps.

Dynamic generated control in UpdatePanel

Hi,

I have an updatepanel, a datagrid (initially whose visible property is false) and few buttons on a webpage. On click of one of button I bind the panel with a collection and set visible property to true in turn displaying bounded datagrid.

-Now when I go to view html source for the page I didn't find any grid(or its table equivalent) control there. Why so? I want to know how new rows are displayed without any corresponding markup generated in the html source?

-Now on click of another button I dynamically create a template column in the datagrid and adds some dynamically generated controls say checkbox in that column of the datagrid. Now my questions are :-

--How can I use those dynamically generated controls in my server side code?

--How can I access them in javascript so as to find out which checkboxes are checked and which are not?

--That newly added column is visible till grid is not updated. How can I make newly generated column persists permanently?

-Also I have added CheckedChanged event handler on that dynamic check box but that event doesn't fire. How can I get that event work?

Sorry for a long post.

Thanks in advance.


1. You don't see the HTML because you're only seeing the original HTML the page first rendered with. The update caused by the update panel is done dynamically with script. That is, the HTML content of the page is altered at runtime, and you're only seeing the request time HTML.

2a. You should follow the link to my blog in my signature and read about dynamically creating server controls. Using the controls is easy -- you created them, that means you have a reference to them.

2b. You know their client side IDs with the ClientID property. You can use the ClientID property to render out javascript that uses it. You can pass the ID to document.getElementById or use the shortcut for that, $get. For example, $get("<%= MyControl.ClientID%>");. Exactly how you do this depends on your needs -- but the basic idea is to render the ClientID into javascript code, by whatever means.

2c. Dynamically created controls do not recreate themselves on postbacks, and that includes asynchronous postbacks from an UpdatePanel. When you dynamically create a control it is up to you to make sure that control is recreated each and every request. Creating them from an event handler isn't enough, because that event won't fire again on a postback unless the user performs the same action. Read my articles on dynamic controls to get some ideas of how to handle this better.

3. It doesn't fire because it doesnt exist... for the reason in 2c.

Hope that helps :)


If you'd Like to see the HTML of the partial-render i suggest using opera (http://www.opera.com/) and download the Developer Console and DOM Snapshot plugins for it. It'll allow you to take a snapshot of the DOM of the page at any given moment, not just the original source.

Hello,

I am new to this forun, I have tried my best to explain my problem but sorry for long description.

I am also facing the same problem, dynamically generated server side code is not reflected in the HTML.

I am using AJAX on that page, if enablepartialrender = false then it works fine.

in the custom control i am adding dynamic control as follows.

protectedoverridevoidCreateChildControls{

StringBuilder builder = new StringBuilder();

builder.Append("some script");.

builder.Append("some html");

LiteralControl ctrl =newLiteralControl(builder.ToString());

Controls.Add(ctrl); }

this control is added on page with UpdatePanel & ScriptManger , now I am modifying the builder contents dynamically , during poastback,

but when I check the view source I am it shows me the original source.

I am gone though all your documents about following

Part 1: Dynamic vs. Static
Part 2: Creating Dynamic Controls
Part 3: Adding Dynamic Controls to the Control Tree

but I haven't found any thing which solves my this issue,

I mean in case of AJAX how to add dynamic controls?


The original HTML source is never going to change. The HTML is dynamically updated with javascript as the result of a partial update. The result is, the browser displays the new HTML, but the "source" of the page is unchanged. With a regular postback, the entire source is redownloaded, so you see the updates with View Source. I hope that makes sense.

As for why or why not you are actually seeing the new content (isn't clear whether thats the case), you'll have to post some more code so we can figure that out. But one thing I notice, you have builder.Append("some script"). Statically written script in the html isn't going to execute.. you will need to use the ScriptManager.Register_ APIs (e.g. RegisterStartupScript), or the script simply won't execute. The reason is because browsers do not execute script in dynamically injected HTML, they have to be dealt with specially, which the framework handles for you if you just use the correct API.


Thanks for quick reply,

Following is the code of custom control. In the CreateControl method I am generating the HTML

also m_listItems this list contents are set from page where I am putting this control.

I am modifying this list on postback, now here is the problem , if I debug the code the i found that every thing is OK

but in the browser those changes are not reflecting , when AJAX is enabled.

Please suggest me solution.

--Kiran

-------- Custom Control Code ----------------

[assembly: WebResource("TestNameSpace.CustomControl.ctrl.js", "text/javascript")]

namespace AtlasWeb.MultiSelectDropDown
{
[ParseChildren(true, "ListItems")]
public class CustomControl : CompositeControl, IScriptControl
{
private ArrayList m_listItems = new ArrayList();
private ScriptManager sm;
private StringBuilder builder = new StringBuilder();

public ArrayList ListItems
{
get { return m_listItems; }
set { m_listItems = value; }
}

protected override void OnPreRender(EventArgs e)
{
if (!this.DesignMode)
{
// Test for ScriptManager and register if it exists
sm = ScriptManager.GetCurrent(Page);

if (sm == null)
throw new HttpException("A ScriptManager control must exist on the current page.");

sm.RegisterScriptControl(this);
}

base.OnPreRender(e);
}

protected override void CreateChildControls()
{
CreateControl();
LiteralControl ctrl = new LiteralControl(builder.ToString());
Controls.Add(ctrl);
}

protected override void Render(HtmlTextWriter writer)
{
base.Render(writer);
if (!this.DesignMode)
{
sm.RegisterScriptDescriptors(this);
}
}

protected virtual IEnumerable<ScriptReference> GetScriptReferences()
{
ScriptReference htmlEditorReference = new ScriptReference("TestNameSpace.CustomControl.ctrl.js", "TestNameSpace.CustomControl");
return new ScriptReference[] { htmlEditorReference };
}

protected virtual IEnumerable<ScriptDescriptor> GetScriptDescriptors()
{
ScriptControlDescriptor descriptor = new ScriptControlDescriptor("TestNameSpace.CustomControl", this.ClientID);
return new ScriptDescriptor[] { descriptor };
}

IEnumerable<ScriptReference> IScriptControl.GetScriptReferences()
{
return GetScriptReferences();
}

IEnumerable<ScriptDescriptor> IScriptControl.GetScriptDescriptors()
{
return GetScriptDescriptors();
}

protected void CreateControl()
{
builder.Append("<script language=\"Javascript\">var ms1 = new TestNameSpace.CustomControl([");
int index = 1;
foreach (ListItemData itemData1 in m_listItems)
{
builder.Append("{name:\"");
builder.Append(itemData1.CtrlID.ToString());
builder.Append("\", value: \"");
builder.Append(itemData1.Value.ToString());
builder.Append("\", isSelected: ");
builder.Append(itemData1.IsSelected.ToString());

if (index == m_listItems.Count)
builder.Append("}");
else
builder.Append("},");

index++;
}

builder.Append("],\"ms1\", \"ms1\", \"" + this.ID + "\");");
builder.Append("Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(pageLoaded);");
builder.Append("function pageLoaded(sender, args)");
builder.Append("{");
builder.Append("javascript:ms1.RenderHtml();");
builder.Append("}");
builder.Append("</script>");
}
}

/// <summary>
/// Summary description for ListItems.
/// </summary>
public class ListItemData : Control
{
#region Constructors

public ListItemData()
{
m_ID = string.Empty;
m_value = string.Empty;
m_isSelected = "false";
}

#endregion

#region public properties

public string CtrlID
{
get { return m_ID; }
set { m_ID = value; }
}

public string Value
{
get { return m_value; }
set { m_value = value; }
}

public string IsSelected
{
get { return m_isSelected; }
set { m_isSelected = value; }
}

#endregion

#region private class data

private string m_ID;
private string m_value;
private string m_isSelected;

#endregion
}
}
-------- Custom Control Code ----------------


Right... the problem is what I said. You are registering your script by rendering it directly into the HTML from your control, because you just add the script to a literal control. That definitely will not work in an update panel. You have a script descriptor there-- but you aren't using it. That script descriptor will cause an instance of your client side control to be created. All you need to do is feed it the data you want though a property on the client side control. Then you assign the data to a property on the script descriptor (AddProperty or something like that). Then the control is created that value will have been set. Here...

MyType = function(element) {
MyType.initializeBase(this, [element]);
}
MyType.prototype = {
_data: null,
get_data: function() { return this._data; },
set_data: function(value) { this._data = value; },

initialize: function() {
var data = this.get_data();
// render the data, or whatever you want to do with it
MyType.callBaseMethod("initialize");
}

}
MyType.registerClass("MyType", Sys.UI.Control);

Then on the server side you feed that property with your ScriptControlDescriptor something like so:

// build up an array of items where each item is a dictionary
ArrayList data = new ArrayList();
Hashtable ht = new Hashtable();
ht["name"] = "name";
data.Add(ht);
// ... add more
ScriptControlDescriptor d = new ScriptControlDescriptor("MyType", this.ClientID);
d.AddProperty("data", data);
return new ScriptDescriptor[] { d };


Hello,

Thanks for reply.


Now when from server side any property is modified, does it reflect at client sie?

I mean on client side I am able to see the property vales, which are set when page is loaded.

now on some event i am modifying that property value, does it reflect at client side?

Currently this is not happening in my code.


If your component is in an update panel, yes it should be recreated and the initialize method called again. It should have the new server side values because the descriptor is recreated.

If you're not seeing that, sorry, you'll have to provide some more examples.


Hello,

Thanks for reply.

I have tested by putting alert in the javascript , it is showing that property vale is updating on event, but not refleting it at client side.

Initialise & despose methods are getting called , when I do button click first despose is called and then initialise is called.

Are there any sample applications or document availble on net for the same?

please let me know.

dynamic generated clientside javascript

hi,

how can i register a script on asyncPostBack and can check in the next asynPostback if the script is on side ?

i use ajax with scriptmanager and updatepanel on my website.

sometimes i will give the user (after a asyncPostBack) a alert-message about javascript...

i have tryed following:

PrivateSub RegisterMsg(ByVal strMessageAsString,ByVal strScriptTagAsString)

Dim strScriptAsString ="alert(""" & strMessage &""");"

If (Not Page.ClientScript.IsClientScriptBlockRegistered("key"))Then

ScriptManager.RegisterClientScriptBlock(Me,Me.GetType(),"key", strScript,True)

EndIf

EndSub

the IsClientScriptBlockRegistered-methode every time gives false back...thx

Use ScriptManager.RegisterStartupScript() and drop the IsBlockRegistered check.


now i have:

Private Sub RegisterMsg(ByVal strMessage As String, ByVal strScriptTag As String)
Dim strScript As String = "alert(""" & strMessage & """);"

If (Not Page.ClientScript.IsClientScriptBlockRegistered("key")) Then
ScriptManager.RegisterStartupScript(Me, Me.GetType(), "key", strScript, True)
End If
End Sub

and it is the same...it did not work correct, the IsClientScriptBlockRegistered-Method returns every time false and because of this the script will be written a second one, and third one and so on...


Hi,

Since the script is created dynamically, it won't be persisted between different requests.

So, before the method is called on the second request, this script block does not exist.

And my suggestion is you don't have to call this multiple times, just call it on initial request and it'll always stay on the page since the page isn't fully refreshed.


the problem is that the appl. dont makes really postbacks during running, only partial postbacks...

and my wish is that i will register and unregister scripts during partial postbacks...how can i do it ?


For partial postback, you can register new scripts.

But you can't unregister existed scripts on server side.


Has there been any progress made on this issue? I am just experiencing this now.

I've overriden OnInit with the following (similar) code:

if (!Page.ClientScript.IsClientScriptBlockRegistered(typeof(Page),"MyScript")
{
// use StringBuilder/StringWriter to build script
ScriptManager.RegisterClientScriptBlock(this,typeof(Page),"MyScript",sb.ToString(),true);
}
 
But the conditional is always true so the script gets recreated every time there is an asyncPostback.
One thing I noticed (using Firebug in Firefox) is on the initial load of the page the script is created
within the form and then on each successive asyncPostback a new script is created in the <head>.
Why is there no IsClientScriptBlockRegistered function in the ScriptManager class? Is that the problem?
That the Page.ClientScript and ScriptManager are looking at two different collections of scripts?

Dynamic Extenders in AJAX beta - Please Help!

Ive managed to update my site to AJAX beta and ive got everything up and running again except for dynamic extenders! Please can anyone help, this driving me nuts!!!

Im trying to create a dynamic list of news feeds, organised by category. Where each category has its own collapsible extender.

In ATLAS i could just do this:

<asp:RepeaterID="RepeaterNewsCategorys"runat="server"DataSourceID="SqlAllNewsSourceCategorys">

<ItemTemplate>

<trclass="ItemTitle">

<tdalign="left">

<b><asp:LabelID="lblNewsCategory"runat="server"><%#Eval("Name")%></asp:Label></b>

</td>

<tdalign="right">

<asp:ImageID="imgNewsCategory"runat="server"/>

</td>

</tr>

<tr>

<tdcolspan="2">

<asp:PanelID="PanelNewsCategory"runat="server">

<asp:CheckBoxListID="chkNewsCategoryFeeds"runat="server"DataTextField="Name"DataValueField="ID"OnDataBound="chkNewsFeeds_DataBound"OnSelectedIndexChanged="chkNewsFeeds_SelectedIndexChanged"></asp:CheckBoxList>

</asp:Panel>

<AtlasControl:CollapsiblePanelExtenderID="CollapsibleNewsCategory"runat="Server">

<AtlasControl:CollapsiblePanelPropertiesTargetControlID="PanelNewsCategory"ExpandControlID="imgNewsCategory"CollapseControlID="imgNewsCategory"Collapsed="True"TextLabelID="lblNewsCategory"

ImageControlID="imgNewsCategory"ExpandedImage="../Images/Icons/Collapse.jpg"CollapsedImage="../Images/Icons/Expand.jpg"/>

</AtlasControl:CollapsiblePanelExtender>

</td>

</tr>

</ItemTemplate>

</asp:Repeater>

Nice and easy and everything worked fine. Now after updating to AJAX beta, none of the collapsible extenders are rendered and none of the images are loaded.

I read another post about dynamic extenders, and tried to create the extenders in the repeaters ItemDataBound.

<asp:RepeaterID="RepeaterNewsCategorys"runat="server"DataSourceID="SqlAllNewsSourceCategorys">

<ItemTemplate>

<trclass="ItemTitle">

<tdalign="left">

<b><asp:LabelID="lblNewsCategory"runat="server"><%#Eval("Name")%></asp:Label></b>

</td>

<tdalign="right">

<asp:ImageID="imgNewsCategory"runat="server"/>

</td>

</tr>

<tr>

<tdcolspan="2">

<asp:PanelID="PanelNewsCategory"runat="server">

<asp:CheckBoxListID="chkNewsCategoryFeeds"runat="server"DataTextField="Name"DataValueField="ID"OnDataBound="chkNewsFeeds_DataBound"OnSelectedIndexChanged="chkNewsFeeds_SelectedIndexChanged"></asp:CheckBoxList>

</asp:Panel>

</td>

</tr>

</ItemTemplate>

</asp:Repeater>

Code Behind:

ProtectedSub RepeaterNewsCategorys_ItemDataBound(ByVal senderAsObject,ByVal eAs System.Web.UI.WebControls.RepeaterItemEventArgs)Handles RepeaterNewsCategorys.ItemDataBound

'Find Controls

Dim holdExpandLabelAs Label

Dim holdExpandImageAs Image

Dim holdExpandPanelAs Panel

Dim holdExpandExtenderAs CollapsiblePanelExtender

holdExpandLabel =CType(e.Item.FindControl("lblNewsCategory"), Label)

holdExpandImage =CType(e.Item.FindControl("imgNewsCategory"), Image)

holdExpandPanel =CType(e.Item.FindControl("PanelNewsCategory"), Panel)

'Create CollapsiblePanelExtender object

holdExpandExtender =New CollapsiblePanelExtender()

'Set properties of CollapsiblePanelExtender

holdExpandExtender.ID ="cpe" & holdExpandPanel.ID

holdExpandExtender.TargetControlID = holdExpandPanel.ID

holdExpandExtender.CollapseControlID = holdExpandImage.ID

holdExpandExtender.ExpandControlID = holdExpandImage.ID

holdExpandExtender.ImageControlID = holdExpandImage.ID

holdExpandExtender.CollapsedImage ="../Images/Icons/Expand.jpg"

holdExpandExtender.ExpandedImage ="../Images/Icons/Collapse.jpg"

holdExpandExtender.Collapsed =True

'Add CollapsiblePanelExtender

e.Item.Controls.Add(holdExpandExtender)

But still nothing. Please can anyone help, ive run out of ideas and im tempted to go back to ATLAS at this point!

Please see the "Known Issue" post at the top of this forum. It addresses this issue.

Dynamic extenders - CollapsiblePanelExtender in ItemTemplate

Hello everybody,

I am new in this forum and that's my first post...

I am using formview(line 30) and inside the ItemTemplate I have put CollapsiblePanelExtenders(line 45).

The thing is that on the page load the form view shows the empty template and once the form view has data, the collapsible panels does not work - the header and the content are visible and the header panel does not react to mouse clicks - like I have no extenders.

I do want to mention the following facts:

1. I haveworking collapsible panels outside the form view(lines 1,6)

2. the form view is inside update panel (conditional update mode - line 28)

I guess the thing is that the form view extenders loaded dynamically and are not registered in the script manager...
I have the same problem with the popup extender as well (loaded dynamically) so maybe I miss something substantial...?

Below is my code.

Thanks a lot!

1<%--static extender ( always on page ) and works perfect--%>2 <ajaxToolkit:CollapsiblePanelExtender ID="ajaxCPExtCampDetails" runat="Server" TargetControlID="CampDetails_ContentPanel"3 ExpandControlID="CampDetails_HeaderPanel" CollapseControlID="CampDetails_HeaderPanel"4 ImageControlID="CampDetails_ToggleImage" ExpandedImage="~/img/collapse.jpg" CollapsedImage="~/img/expand.jpg"5 SuppressPostBack="true" Collapsed="true" />6<%--static extender ( always on page ) and works perfect--%>7 <ajaxToolkit:CollapsiblePanelExtender ID="ajaxCPExtCampSummeries" runat="Server"8 TargetControlID="CampSummeries_ContentPanel" ExpandControlID="CampSummeries_HeaderPanel"9 CollapseControlID="CampSummeries_HeaderPanel" ImageControlID="CampSummeries_ToggleImage"10 ExpandedImage="~/img/collapse.jpg" CollapsedImage="~/img/expand.jpg" SuppressPostBack="true"11 Collapsed="false" />12 <asp:Panel ID="CampSummeries_HeaderPanel" runat="server" Height="20px" Width="800px"13 BackColor="#C0C0FF">14 <div class="CollapsibleHeaderPanel">15 <asp:Image ID="CampSummeries_ToggleImage" runat="server" ImageUrl="~/img/collapse.jpg" />16 <asp:Label ID="CampSummeries_ToggleLabel" runat="server" SkinID="lblHdrPnl">Campaigns Summeries</asp:Label>17 </div>18 </asp:Panel>19 <asp:Panel ID="CampSummeries_ContentPanel" runat="server" Width="800px">20 <asp:Panel ID="CampDetails_HeaderPanel" runat="server" Width="800px" Height="20px"21 BackColor="#C0C0FF">22 <div class="CollapsibleHeaderPanel">23 <asp:Image ID="CampDetails_ToggleImage" runat="server" ImageUrl="~/img/collapse.jpg" />24 <asp:Label ID="CampDetails_ToggleLabel" runat="server" SkinID="lblHdrPnl">Campaign Details</asp:Label>25 </div>26 </asp:Panel>27 <asp:Panel ID="CampDetails_ContentPanel" runat="server" Width="800px">28 <asp:UpdatePanel ID="UpdatePanelCampDetails" runat="server" UpdateMode="Conditional">29 <ContentTemplate>30 <asp:FormView ID="fvDetails" runat="server"31 DataSourceID="odsDetails" Width="800px" BackColor="Transparent" DefaultMode="ReadOnly"32 OnDataBound="fvDetails_DataBound" OnItemCommand="fvDetails_ItemCommand">33 <EditItemTemplate>34 Empty35 </EditItemTemplate>36 <InsertItemTemplate>37 InsertItemTemplate - Not implemented yet38 </InsertItemTemplate>39 <ItemTemplate>40 <div style="padding-left: 10px">4142<%---------------------%>43 <%-------thie one does not work--------%>44 <%--------Loaded dynamically----------%>45 <ajaxToolkit:CollapsiblePanelExtender runat="server" ID="ajaxCPExtBasisFieldsVS1P"46 TargetControlID="BasisFieldsVS1P_ContentPanel"47 ExpandControlID="BasisFieldsVS1P_HeaderPanel"48 CollapseControlID="BasisFieldsVS1P_HeaderPanel"49 ImageControlID="BasisFieldsVS1P_ToggleImage"50 ExpandedImage="~/img/collapse.jpg"51 CollapsedImage="~/img/expand.jpg"52 SuppressPostBack="True"53 Collapsed="True" />54 <asp:Panel ID="BasisFieldsVS1P_HeaderPanel" runat="server" Width="750px">55 <div class="CollapsibleHeaderPanel">56 <asp:Image ID="BasisFieldsVS1P_ToggleImage" runat="server" ImageUrl="~/img/collapse.jpg" />57 <asp:Label ID="BasisFieldsVS1P_ToggleLabel" runat="server" SkinID="lblHdrPnl" Text="<%$ Resources:AdminVSMI1Res, BasisFields%>"></asp:Label>58 </div>59 </asp:Panel>60 <asp:Panel ID="BasisFieldsVS1P_ContentPanel" runat="server" Width="750px">61 some binded content62 </asp:Panel>63 </div>64 <asp:LinkButton ID="UpdateButton" runat="server" CausesValidation="True" CommandName="Update"65 Text="Update">66 </asp:LinkButton>67 <asp:LinkButton ID="UpdateCancelButton" runat="server" CausesValidation="False" CommandName="Cancel"68 Text="Cancel">69 </asp:LinkButton>70 </ItemTemplate>71 <EmptyDataTemplate>72 No campaign was chosen.73<%---%>74 </EmptyDataTemplate>75 </asp:FormView>76 </ContentTemplate>77 <Triggers>78 <asp:AsyncPostBackTrigger ControlID="gvVS1P" EventName="SelectedIndexChanged" />79 </Triggers>80 </asp:UpdatePanel>81 </asp:Panel>82 </asp:Panel>83
Maybe:http://forums.asp.net/thread/1441672.aspx

Dynamic DragPanel Positioning

I'm back to revisiting this issue of positioning dynamically generated DragPanels. It has been suggested to use tables for the layout; however, I'm don't know how to go about doing this. Everything is dynamically generated, so the table needs to be as well.

I am using MasterPages and I'm trying to obtain a layout like below for example in my ContentPlaceHolder.

--------------------------------------------------------

Header Section

--------------------------------------------------------
Menu Section |
| Panel1 Panel2 Panel3 Panel 4
|
|
| Panel5 Panel6
|
|
| Panel7 Panel8 Panel9 Panel10
|
|
| Panel11 Panel12 Panel13
|
|

I am using the following code to generate the DragPanels. The number of DragPanels generated depends on the total count in the array.

for (int i = 0; i < portletRptArray.Length; i += 3)
{
// Setup up the Portlet Header Label Label headerLabel =new Label();
headerLabel.ID ="headerLabel" + i.ToString();
headerLabel.BackColor = System.Drawing.Color.Blue;
headerLabel.ForeColor = System.Drawing.Color.White;

if (i == 0)
{
continue;
}
else { headerLabel.Text = portletRptArray[i + 2].ToString(); headerLabel.Width = Unit.Percentage(portletRptArray[i].Length * 2); }// Setup up the Portlet Header Panel headerPanel =new Panel();
headerPanel.ID ="headerPanel" + i.ToString();
headerPanel.BorderColor = System.Drawing.Color.Blue;
headerPanel.Height = Unit.Pixel(20);
headerPanel.Style.Add("cursor","move");
headerPanel.Controls.Add(headerLabel);

// Setup up the Portlet Body Panel pnlBody =new Panel();
pnlBody.ID ="pnlBody" + i.ToString();
pnlBody.BackColor = System.Drawing.Color.LightGray;
pnlBody.BorderColor = System.Drawing.Color.Blue;
pnlBody.ForeColor = System.Drawing.Color.Black;
pnlBody.BorderWidth = 1;
pnlBody.Height = Unit.Pixel(200);
pnlBody.Style.Add("position","absolute");
pnlBody.Style.Add("left", Unit.Pixel(portletRptArray[i].Length * 20).ToString());
pnlBody.Style.Add("top","200px");
pnlBody.Controls.Add(headerPanel);

// Setup the DragPanel Extender AjaxControlToolkit.DragPanelExtender dPanel =new AjaxControlToolkit.DragPanelExtender();
dPanel.ID ="dPanel" + i.ToString();
dPanel.TargetControlID = pnlBody.ID;
dPanel.DragHandleID = headerPanel.ID;

// Add the DragPanels, DragPanel Extender, and PortletPanel to the Page. portletPanel.Controls.Add(pnlBody); portletPanel.Controls.Add(dPanel);this.Form.Controls.Add(pnlBody);
this.Form.Controls.Add(dPanel);
}

Can someone please show me how I can accomplish this with the above code? This has been really frustrating me.Confused

Can anyone help me with this? It may be a simple task, but I'm having a tough time trying to accomplish it.


No one has any ideas about how to do this?


Hi Lspence,

My understanding of your issue is that you want to make the automatically generated Panel shown as what you described above. If I have misunderstood, please feel free to let me know.

Based on my experience, I think the easiest way is add a Table control to your aspx page and make it work as a container for the generated Panel. So now you can use CSS to control its showing position.

Also you can set the Panel's showing position directly on server side. For example,

Panel1.Attributes.CssStyle.Add("position", "absolute");
Panel1.Attributes.CssStyle.Add("left", "100px");
Panel1.Attributes.CssStyle.Add("top", "100px");

Here is thesimilar thread that you can refer to.

I hope this help.

Best regards,

Jonathan


Thanks for the reply Jonathan. I remember my previous thread, I probably should have just continued this there. Anyway, after discussing this approach with a co-worker I realized that a table won't actually work well here. The reason is because the panels will be placed in each cell to achieve the layout, but they are DragPanels, so when they get moved out of the cell the table will become distorted. I was able to implement a small placing algorithm that allows for the desired placement, but it still needs some tweaking.

I do have another question though. Each DragPanel will act like a portlet, so since everything is dynamically generated how can I dynamically generate the mini-tables for each panel?

Here's an example of how one of the DragPanel's might look:

----------
| Sales Percent |
----------
| Total | 8270% |
| North | 580% |
| East | 2390%|
| South | 3200%|
| West | 2100% |
----------


Hi Lspence,

Thanks for sharing your experience. I agree with you that use TableCell to fix the Panel's position is not the best solution in your situation. You can set the Panel's absolute position on server side. Just like my second suggestion. But It's complex, isn't it?

Here is the sample to generate the Table which is use to display the information and the panel is inside the Panel.

<%@. 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"> protected void Page_Load(object sender, EventArgs e) { TableRow myTableRow1 = new TableRow(); TableCell tbCell1 = new TableCell(); tbCell1.Text = "Title1"; tbCell1.Style.Add("border-right-style", "none"); myTableRow1.Cells.Add(tbCell1); TableCell tbCell2 = new TableCell(); tbCell2.Text = "Title2"; tbCell2.Style.Add("border-left-style", "none"); myTableRow1.Cells.Add(tbCell2); this.Table1.Rows.Add(myTableRow1); //add loop here; while() state is preferred. TableRow myTableRow2 = new TableRow(); TableCell tbcell3 = new TableCell(); tbcell3.Text = "111"; TableCell tbcell4 = new TableCell(); tbcell4.Text = "222"; tbcell4.Attributes.Add("align", "center"); myTableRow2.Cells.Add(tbcell3); myTableRow2.Cells.Add(tbcell4); this.Table1.Rows.Add(myTableRow2); }</script><html xmlns="http://www.w3.org/1999/xhtml" ><head runat="server"> <title>Untitled Page</title></head><body> <form id="form1" runat="server"> <asp:Table ID="Table1" runat="server" Border="1" BorderColor="black" CellPadding="0" CellSpacing="0" Width="50%"> </asp:Table> </form></body></html>

I hope this help.

Best regards,

Jonathan


Thank you Jonathan, this has been very helpful.

Dynamic display behaviors for dragDropList

I'm using the drag drop list to allow my users to reposition report elements. The problem that I am having is that different zones have different sizes and we would like our draggable elements to resize to fill the zone in which they are dropped. Unfortunately, the controls are retaining their original sizes when moved to a different drop zone.

Furthermore, we have implemented som cascading styles to allow the controls to change appearance depending on which zone they have been places. This is not working either, the controls always retaing the style of the zone in which they were originally placed.

Any suggestions?

Yeah, you should build a behavior that implements the IDropTarget interface, and assign that behavior to whatever Divs you've go tthat are going to be the drop zones for your parts. The custom behavior you build has to implement this.drop() , among others, and that funciton will define what happens when something's dropped on it. My guess is that you'd build logic into the drop() method that tells the div that was dropped to resize / restyle itself, possibly by just changing the cssClass . Check out this article: http://www.codeproject.com/Ajax/AtlasDragNDrop.asp for more info.

Dynamic Data in Accordion Control

Hi guys,

I'm trying to populate dynamic data into the AJAX Accordion control. What I want is values taken from my db and posted into the Accordion panels (perhaps 20 to 30 panels per page). I can manage the paging issue (page 1, page 2, page 3 etc.) but how do I take a value from the database, place it in the header, then pick another column from the same row and place it into content, and then move onto the next row?

Any ideas?

Hello,

I made some study,

I could add dynamically it's header and content through the code.

Anyway, it works for me. if contents are simple I think O.K.

Following test code was in the Page_Load event. (VB, but code is very simple for C# to read)

Dim acdAs AjaxControlToolkit.Accordion =Me.FindControl("Accordion2")Dim pAs New AjaxControlToolkit.AccordionPaneDim lAs New Label l.Text ="content test"Dim l2As New Label l2.Text ="header test"Dim inpAs New HtmlInputButton("image")With inp .ID ="myImage_2" .Attributes.Add("src","../images/4-0.gif")End With p.HeaderContainer.Controls.Add(l2) p.HeaderContainer.Controls.Add(inp) p.ContentContainer.Controls.Add(l) acd.Panes.Add(p)

Thanks mate.

It makes sense, but I'm ending up with an error using the exact same code that you providedTongue Tied At runtime:

Server Error in '/' Application.

Object reference not set to an instance of an object.

Description:An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details:System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:

Line 24: Line 25:Line 26: acd.Panes.Add(p)

Any idea what seems to be going wrong here?


Okies i think I've worked this out. For some reason My.FindControl wasn't working for me so I changed the code to this instead:

Protected Sub Page_Load(ByVal senderAs Object,ByVal eAs System.EventArgs)Dim pAs New AjaxControlToolkit.AccordionPaneDim hAs New Label h.Text ="header text"Dim cAs New Label c.Text ="container text" p.HeaderContainer.Controls.Add(h) p.ContentContainer.Controls.Add(c) Accordion1.Panes.Add(p) Application("prodtype") = ProductTypeList.SelectedItem.TextEnd Sub

A reference directly to the Accordion control id helped. Many thanks for the help.

Cheers!

Dynamic Creation of CollapsablePanels

I'd like to know how to create a CollapsablePanel in code-behind. My goal is to fetch records from a SQL 05 DB, and create a panel for each record/row in the dataset. I don't know how many rows I'll have, if any, and this means I need to do it on the back end, not in the XHTML code.

Hi,

I made the following sample according to your requirements, please try it:

<%@. 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"> protected void Page_Load(object sender, EventArgs e) { int numberOfRecordsToBeShown = 10; // this value can be determined by the number of rows in database for (int i = 0; i < numberOfRecordsToBeShown; i++) { Panel pnl = new Panel(); Label lblContent = new Label(); LinkButton lbHeader = new LinkButton(); PlaceHolder1.Controls.Add(lbHeader); PlaceHolder1.Controls.Add(pnl); pnl.Controls.Add(lblContent); lbHeader.ID = "Header" + i.ToString(); lbHeader.Text = "Header" + i.ToString(); pnl.ID = "Row" + i.ToString(); lblContent.Text = "Content to be shown"; AjaxControlToolkit.CollapsiblePanelExtender cpe = new AjaxControlToolkit.CollapsiblePanelExtender(); cpe.ID = "Extender" + i.ToString(); cpe.SuppressPostBack = true; cpe.CollapseControlID = lbHeader.ID; cpe.ExpandControlID = lbHeader.ID; cpe.TargetControlID = pnl.ID; PlaceHolder1.Controls.Add(cpe); } }</script><html xmlns="http://www.w3.org/1999/xhtml" ><head runat="server"> <title>Untitled Page</title></head><body> <form id="form1" runat="server"> <div> <asp:ScriptManager ID="ScriptManager1" runat="server"> </asp:ScriptManager> </div> <asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder> </form></body></html>
Hope this helps.

I gave it a go, but all I get is 10 lines of 'Content to be shown' on my screen. No collapsing/expanding... nothing, really, except 10 lines of text.


ok, with a few slight alterations, I wound up with this:

protected void Page_Load(object sender, EventArgs e) {
SpewOutCollapses();
}

public void SpewOutCollapses() {
int numberOfRecordsToBeShown = 5; // this value can be determined by the number of rows in database
for (int i = 0; i < numberOfRecordsToBeShown; i++) {
AjaxControlToolkit.CollapsiblePanelExtender cpe = new AjaxControlToolkit.CollapsiblePanelExtender();
StringBuilder sBuild = new StringBuilder();

Panel pnlContainer = new Panel();
Panel pnlHeaderGoal1Update = new Panel();
Label lblContent = new Label();
LinkButton lbHeader = new LinkButton();
PlaceHolder1.Controls.Add(lbHeader);
PlaceHolder1.Controls.Add(pnlContainer);
pnlContainer.Controls.Add(pnlHeaderGoal1Update);
pnlHeaderGoal1Update.Controls.Add(lblContent);

pnlContainer.ID = "pnlContainer" + i.ToString();
pnlContainer.Style.Add("background", "#DFDFDF");

lbHeader.ID = "Header" + i.ToString();
sBuild.Append(" <table class=\"clsOneHundredPercentWide clsBGGreyA clsCursorPointer txtWhiteBold\" style=\"height: 25px;\">");
sBuild.Append(" <tr>");
sBuild.Append(" <td class=\"clsTwoByFivePadding cls25pxHigh clsBold clsLeftAlign\" style=\"width: 15%\">ID " + i.ToString() + "</td>");
sBuild.Append(" <td class=\"clsTwoByFivePadding cls25pxHigh clsLeftAlign\" style=\"width: 85%\">(Show Details...)</td>");
sBuild.Append(" </tr>");
sBuild.Append(" </table>");
lbHeader.Text = sBuild.ToString();

pnlHeaderGoal1Update.ID = "pnlHeaderGoal1Update" + i.ToString();

lblContent.Text = "<div class=\"clsTwoByFivePadding clsLeftAlign\" style=\"padding-right: 10px;\">";
lblContent.Text += " <p>Quisque felis lacus, sodales in, commodo ut, pellentesque sed, orci. Pellentesque congue nisi sed enim. Quisque congue sodales sapien. Suspendisse et lorem ut erat dignissim vestibulum. In hac habitasse platea dictumst. Sed nisl neque, convallis eu, sagittis dignissim, molestie eu, odio. Fusce quam orci, vehicula sollicitudin, tincidunt sed, lobortis dignissim, lectus. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Sed interdum tincidunt mi. Vivamus blandit molestie lectus. Praesent sem lacus, tincidunt nec, placerat ac, feugiat non, tortor. Donec eu pede in neque viverra iaculis. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Integer interdum augue quis risus. Pellentesque malesuada elit et eros. In ipsum. Pellentesque eget diam. Aenean quis lorem. Cras et dolor at urna pharetra nonummy. Sed posuere, risus eget suscipit lacinia, ipsum nulla adipiscing sapien, vitae aliquet lacus arcu blandit neque.</p>";
lblContent.Text += "</div>";

cpe.ID = "Extender" + i.ToString();
cpe.SuppressPostBack = true;
cpe.CollapseControlID = lbHeader.ID;
cpe.ExpandControlID = lbHeader.ID;
cpe.TargetControlID = pnlHeaderGoal1Update.ID;
PlaceHolder1.Controls.Add(cpe);
}
}

It works great, but that brings me to part 2 of my question: Is there a way to generate SUB collapsers in this... to in effect nest collapsing panels in collapsing panels. I can hard-code that, but I would love to generate it. What I want is, inside the existing panel generation, to generate a single collapsablePanel (so that each collapser has one nested collapser inside). Think that's possible?


Ok, let's forget the nesting for the moment, and think instead about something else: can you explain, possibly, why the panels start fully expanded?


Morydyn:

Ok, let's forget the nesting for the moment, and think instead about something else: can you explain, possibly, why the panels start fully expanded?

By default, the initial state is expanded. You can change it to collapsed explicitly.

cpe.ID = "Extender" + i.ToString();
cpe.Collapsed = true;
cpe.SuppressPostBack = true;

Dynamic Creation of AJAX Controls (w/Intellisense?)

Is there any way to make intellisense work for the AJAX Control Toolkit in the code behind pages? I'm trying to dynamically create controls in c#.

Thanks!

Hi Jerryp,

First , I think you should InstallAsp.Net 2.0 Ajax Extension V1.0 and then installAjax Control Toolkit. You can get them from this url: http://www.asp.net/ajax/ . If your project is an exsit which is not an Ajax-Enabled project, you canmodify the web.config and add reference to the AjaxControlToolkit.dll.

By the way, Javascript intellisense is support by VS2008.

Hope this help.

Best regards,

Jonathan


Thanks for your respnose! I already have all those things installed. I guess I should have given more background. I am trying to create the controls in my c# page_load method. When I dynamically create the controls Intellisense doesn't work, so I've been using Reflector to see what methods are available on the different classes. It doesn't really get annoying until you have to drill down through the class hierarchy to find out what a property is called. My code compiles and runs, but it's difficult to develop with the AJAX Control Toolkit if intellisense doesn't work. I would like to know how to get the intellisense for the control toolkit to work.

Thanks,

Jerry

Dynamic created ModalPopup Window

Hi,

I am having a lot of modal popup windows on my page (20+).

When i click various buttons on my page, various modal popupwindows should apear. But I don't want to define all the windows in the aspx, because the windows are pretty large.

So I think it would be fine to place one Panel containing an UpdatePanel and one ModalPopupExtender on the page and on clicking a button on the page i create an composite control and place it inside the Updatepanel, update() and show the modal dialog from code behind. This works fine if the content of the modal popup doesn't contain any buttons. But when i use buttons inside the popup window, their events doesn't fire at all.

Here is some code:

The ASPX:

 <asp:panel id="pnlPopUp" runat="server" style="display: none">
<div style="background-color: LightGrey">
<asp:panel id="header" runat="server">
<asp:label id="lblHeader" runat="server" />
<asp:linkbutton id="lbClose" runat="server" text="X" onclientclick="$find('mpePopUp').hide(); return false;" />
</asp:panel>
<asp:updatepanel runat="server" id="updPopup" childrenastriggers="true" updatemode="conditional">
<contenttemplate>
<asp:panel id="pnlBody" runat="server" cssclass="body" />
</contenttemplate>
</asp:updatepanel>
</div>
</asp:panel>
<cc1:modalpopupextender id="mpePopUp" behaviorid="mpePopUp" popupcontrolid="pnlPopUp" runat="server" dropshadow="true"repositionmode="RepositionOnWindowResizeAndScroll" targetcontrolid="dummy" backgroundcssclass="modalBackground" />

CODE:

public partialclass _Default : System.Web.UI.Page
{
public MDMWindow2 w2 =null;

protected override void OnInit( EventArgs e )
{
base.OnInit( e );
w2 =new MDMWindow2( );
w2.Bubble +=new EventHandler( w2_Bubble );
}

void w2_Bubble(object sender, EventArgs e)
{
int x = 0;// This Point get NEVER hit}protected void ShowWindow2(object sender, EventArgs e )
{
w2.HeaderText ="WWW2";
updPopup.ContentTemplateContainer.Controls.Add( w2 );
updPopup.Update( );
mpePopUp.Show( );
}

and the code of the control:

using System;
using System.Web.UI;
using System.Web.UI.WebControls;

/// <summary>
/// Summary description for PopUpPanel
/// </summary>public class MDMWindow2 : CompositeControl
{
private Label headerLabel;
private Button button;

public String HeaderText
{
get{EnsureChildControls( );return headerLabel.Text;
}
set{EnsureChildControls( );headerLabel.Text =value;
}
}

public MDMWindow2( )
{
}

public event EventHandler Bubble;

protected override void OnLoad( EventArgs e )
{
base.OnLoad( e );
EnsureChildControls( );
}

protected override void CreateChildControls( )
{
EnsureChildControls( );
headerLabel =new Label( );
headerLabel.ForeColor = System.Drawing.Color.Red;
this.Controls.Add( headerLabel );

button =new Button( );
button.CommandName ="Click";
button.Text ="ClickMe";
Controls.Add( button );
button.Click +=new EventHandler( b_Click );

}

void b_Click(object sender, EventArgs e )
{
Bubble(this, e );// This Point get NEVER hit
}
}

Can anybody help? What is wrong with wiring the eventHandlers? Is the updatepanel the probl?em? Or can anybody show me an better way to create modal popups at serverside?

Thnx

I did something like this using user controls (.ascx files). The .aspx file has an UpdatePanel whose content is an asp:Panel with an asp:PlaceHolder in it and an asp:Button. The button is configured with an OnCommand handler and an initial CommandName of 'Inactive'. A LinkButton on the page triggers a partial postback which does 3 main things: a) does a LoadControl of a .ascx file into the Placeholder; b) changes the CommandName of the Button to "EntryForm" (or something logically associated with the .ascx); c) calls Show() on the modal popup.

After the partial rendering completes, the modal popup is shown. When the Button is pressed, the OnCommand is run, and it uses the CommandName to do the right thing for the particular .ascx that was loaded. It's important that in Page_Load, if it's a postback, that the loaded .ascx is re-loaded (using LoadControl) so that the viewstate is restored and the controls on the .ascx can get updated with the values entered on the modalpopup form. During OnCommand, if a different .ascx needs to be shown, it unloads the Placeholder's controls and uses LoadControl for the next .ascx. If the sequence is done, it sets the CommandName back to "Inactive" and hides the modalpopup.

Hope that helps,

Donnie

This sounds good. But in my Dialogs I will have more various controls like dropdownllist or textboxes wich will have to be bound to an eventhandler too. They have to be in the controls.

It would be perfect, if I can handle the events, which are triggered by my control, inside the page.



Sounds like, then, after you use LoadControl, the page just needs to add event handlers in its code-behind to the controls in the .ascx that was dynamically loaded.

Dynamic create UpdatePanel during postback

Hi,

I want to add a UpdatePanel into page dynamically during postback, see bellow code for detail. The problem is although UpdatePanel control was successful created, I cannot get its reference in later postback times.

// dummy template
publicclassMyTemplate :ITemplate
{
publicvoid InstantiateIn(Control container)

{

}

}

// create UpdatePanel during postback
protectedvoid Button5_Click(object sender,EventArgs e)
{

Microsoft.Web.UI.UpdatePanel u =new Microsoft.Web.UI.UpdatePanel();

u.ID ="udpDynamic";

u.ContentTemplate =newMyTemplate();

u.Mode = Microsoft.Web.UI.UpdatePanelMode.Conditional;

Microsoft.Web.UI.ControlEventTrigger trigger =new Microsoft.Web.UI.ControlEventTrigger();

trigger.ControlID ="Button6";// this button is created in design time

trigger.EventName =

"Click";

u.Triggers.Add(trigger);

this.Form.Controls.Add(u);

}

// other postback event
protectedvoid Button6_Click(object sender,EventArgs e)
{

Label test =newLabel();

test.Text ="I'm new portlet " +DateTime.Now.ToLongTimeString();

Microsoft.Web.UI.UpdatePanel u = (Microsoft.Web.UI.UpdatePanel)this.Form.FindControl("udpDynamic");

u.Controls.Add(test);// error! u is null

}

// here is HTML code generated, as I can see the UpdatePanel control was created successfully
<div id="udpDynamic"></div>

<components>
<pageRequestManager id="_PageRequestManager" updatePanelIDs="UpdatePanel1,UpdatePanel2,UpdatePanel3,udpDynamic" asyncPostbackControlIDs="Button4,Button6" scriptManagerID="ScriptManager1" form="form1" />
</components>

Well, I can't solve your problem, but I can tell you one thing that is wrong with your code:

When adding a control to an UpdatePanel, you need to use the ContentTemplateContainer.Controls.Add(...) property of the UpdatePanel, otherwise you will not see the control (in a book I read, it will actually throw an error, but I guess it isn't for you).

I work in VB.NET, although I can usually understand C#, but when I try to convert from System.Web.UI.Control (which is what FindControl returns) to System.Web.UI.UpdatePanel, I receive the following error message:

Unable to cast object of type 'System.Web.UI.Control' to type 'System.Web.UI.UpdatePanel'.

I am surprised that you are not receiving this error as well, if you take a look at my posting athttp://forums.asp.net/t/1154222.aspx you can see more details about this problem I am having. Good Luck!

Dynamic controls problem.

dear All

I have a checkbox (dynamically generated) and a label.

when the checkbox is changed, I want to change the labels text property. and also put a dynamic DropDownlist box on thr form.

when the Dropdownlist box selected value is changed, I want to again change the value of the labels text to something else. The checkbox behaves properly, but the DropDownList box when selected doesnt do ANYTHING. NOTE: I put the label in a update panel and call the panel.update() method. I put both the .cs and .aspx codes below.

aspx code

<%@dotnet.itags.org. Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head runat="server"> <title>Untitled Page</title></head><body> <form id="form1" runat="server"> <asp:ScriptManager ID="ScriptManager1" runat="server" /> <div> <asp:UpdatePanel ID="UpdatePanel1" UpdateMode="Conditional" runat="server"> <ContentTemplate> <asp:PlaceHolder ID="PlaceHolder1" runat="server"> <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label> </asp:PlaceHolder> </ContentTemplate> </asp:UpdatePanel> </div> </form></body></html>


aspx.cs code

using System;using System.Data;using System.Configuration;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Web.UI.HtmlControls;public partialclass _Default : System.Web.UI.Page { CheckBox CheckBox1 =new CheckBox(); DropDownList Dropdownlist1 =new DropDownList();protected void Page_Load(object sender, EventArgs e) { Label1.Text ="page has loaded"; addCheckBox(); CheckBox1.AutoPostBack =true; ScriptManager1.RegisterAsyncPostBackControl(CheckBox1);//adddropdownlist(); CheckBox1.CheckedChanged +=new EventHandler(CheckBox1_CheckedChanged); Dropdownlist1.AutoPostBack =true; ScriptManager1.RegisterAsyncPostBackControl(Dropdownlist1); Dropdownlist1.SelectedIndexChanged +=new EventHandler(DropDownList1_SelectedIndexChanged); }private void adddropdownlist() { Dropdownlist1.Items.Add("first"); Dropdownlist1.Items.Add("second"); Dropdownlist1.Items.Add("thirs"); PlaceHolder1.Controls.Add(Dropdownlist1); }private void addCheckBox() { CheckBox1.Text ="tickme"; CheckBox1.ID ="checkbox1"; PlaceHolder1.Controls.Add(CheckBox1); }void CheckBox1_CheckedChanged(object sender, EventArgs e) { Label1.Text ="checkbox has been ticked"; adddropdownlist(); UpdatePanel1.Update(); }void DropDownList1_SelectedIndexChanged(object sender, EventArgs e) { Label1.Text ="Page has reloaded"; UpdatePanel1.Update(); }}

Thanks in advance,

prasad..

bumping--please help me.

This doesn't have to do with AJAX (try removing the UpdatePanel to see).

I highly recommend this 4-part series on dynamic controls in ASP.NET:http://devsushi.com/2006/08/27/aspnet-dynamic-control-creation-part-1/

The behavior I see with your code is that when I change the dropdown, the page goes back to its initial state ("page has loaded" and a checkbox). This makes sense, because when you change the dropdown, the page posts back, and in that postback, you don't create the dropdown. That means there's no control to hook up to, and the SelectedIndexChanged event doesn't fire. What you need to do is create the dropdown on every postback where you need to use it.

I recommend adding the dropdown to the placeholder in Page_Loadall the time, and setting Dropdownlist1.Visible = false. Then set Dropdownlist1.Visible = true when you want to display it. That way its events will still hook up properly when it causes a postback.

I hope that makes sense, but if it doesn't, the article I pointed to above should help a great deal. This can be confusing.


thank you for the link to the article. now I realise...what really a postback is. This was my first attempt at programming...:)

thank you,

prasad.

Dynamic Controls in ASP.NET AJAX context - Controls seem to be disappearing.

I have a Web Application that I am developing and I have run across aserious problem. Due to the fact that the Application entails a lot ofdetails and code I am not able to give an actual sample of the problemI am running into. However, I have created the same problem on asmaller scale in a temporary Application.

Theissue revolves around ASP.NET AJAX and its ability to track Dynamicallycreated Web Controls. On the sample Application below I have a Pagethat contains 8 Buttons. Whenever one of those Buttons is pressed thePage performs an Async PostBack which causes the Page Load Event toexecute followed by the Event Handler for the Button pressed. In theEvent Handler the Button gets removed from the Page. The desiredeffect is that when someone pressed a Button it will in turn remove theappropriate Web Control (Button) from the Page. Everything works finewith one very big exception: ASP.NET AJAX seems to have a problemkeeping track of the Controls on the page.

For example, if youcopy and paste the code at the bottom of this post into Visual Studioand press the Buttons in the following order you will notice someButtons simply disappearing:
2 - 7 - PostBack - 4 - 1 - PostBack

Onevery important part of this demonstration is that the Button is notonly removed but its also prevented from Rendering. If you take outthis line of code everything works fine but in my actual Applicationthe Control is not Rendered and the results match that of what happensin the temp Application.

So my question is, whats happening inthe background? It seems that removing the Control does not prevent itfrom being Rendered and if you manually prevent it from Rendering bysetting its Visible Property to False then ASP.NET gets completelythrown off as to whats going on.

I know its rather difficult toanswer a question like this because you can't simply provide analternative to the problem so any help is greatly appreciated. I amsimply trying to figure out whats going on in the background so I canfind a solution to my real Application.

Code Behind:

Partial Class _Default
Inherits System.Web.UI.Page

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

' Clearing any previous text.
label1.text = ""

' If its the first time loading the Page
If Not Page.IsPostBack Then
Page.Session.Add("AddButton1", "True")
Page.Session.Add("AddButton2", "True")
Page.Session.Add("AddButton3", "True")
Page.Session.Add("AddButton4", "True")
Page.Session.Add("AddButton5", "True")
Page.Session.Add("AddButton6", "True")
Page.Session.Add("AddButton7", "True")
Page.Session.Add("AddButton8", "True")

Page.Session.Add("RemovalTracker", "")

' Else the page is performing a PostBack
Else
label1.text = CStr(Page.Session.Item("RemovalTracker"))
End If

'Dynamically creating the Buttons and then adding them to the Page / Form.

If CBool(Page.Session.Item("AddButton1")) = True Then
Dim button1 As New Button
button1.Text = "Button1"
button1.ID = "Button1"
AddHandler button1.Click, AddressOf testSub
UpdatePanel1.ContentTemplateContainer.Controls.Add(button1)
End If

If CBool(Page.Session.Item("AddButton2")) = True Then
Dim button2 As New Button
button2.Text = "Button2"
button2.ID = "Button2"
AddHandler button2.Click, AddressOf testSub
UpdatePanel1.ContentTemplateContainer.Controls.Add(button2)
End If

If CBool(Page.Session.Item("AddButton3")) = True Then
Dim button3 As New Button
button3.Text = "Button3"
button3.ID = "Button3"
AddHandler button3.Click, AddressOf testSub
UpdatePanel1.ContentTemplateContainer.Controls.Add(button3)
End If

If CBool(Page.Session.Item("AddButton4")) = True Then
Dim button4 As New Button
button4.Text = "Button4"
button4.ID = "Button4"
AddHandler button4.Click, AddressOf testSub
UpdatePanel1.ContentTemplateContainer.Controls.Add(button4)
End If

If CBool(Page.Session.Item("AddButton5")) = True Then
Dim button5 As New Button
button5.Text = "Button5"
button5.ID = "Button5"
AddHandler button5.Click, AddressOf testSub
UpdatePanel1.ContentTemplateContainer.Controls.Add(button5)
End If

If CBool(Page.Session.Item("AddButton6")) = True Then
Dim button6 As New Button
button6.Text = "Button6"
button6.ID = "Button6"
AddHandler button6.Click, AddressOf testSub
UpdatePanel1.ContentTemplateContainer.Controls.Add(button6)
End If

If CBool(Page.Session.Item("AddButton7")) = True Then
Dim button7 As New Button
button7.Text = "Button7"
button7.ID = "Button7"
AddHandler button7.Click, AddressOf testSub
UpdatePanel1.ContentTemplateContainer.Controls.Add(button7)
End If

If CBool(Page.Session.Item("AddButton8")) = True Then
Dim button8 As New Button
button8.Text = "Button8"
button8.ID = "Button8"
AddHandler button8.Click, AddressOf testSub
UpdatePanel1.ContentTemplateContainer.Controls.Add(button8)
End If

End Sub

Protected Sub testSub(ByVal sender As Object, ByVal e As System.EventArgs)

' Appending the Button Text to SessionState.
Page.Session.Item("RemovalTracker") = Page.Session.Item("RemovalTracker") & " - " & CType(sender, Button).Text

' Building the ID for the Session Item that needs to be modified.
Dim buttonToRemove As String
buttonToRemove = "Add" & CType(sender, Button).ID
Session.Item(buttonToRemove) = "False"

' Preventing the Buttom from Rendering - this is CRUCIAL to my demonstration.
CType(sender, Button).Visible = False

Page.Form.Controls.Remove(CType(sender, Button))

End Sub

End Class

Default.aspx Page:
<%@dotnet.itags.org. Page Language="VB" AutoEventWireup="true" CodeFile="Default.aspx.vb" Inherits="_Default" %
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
</head>
<body
<form id="form1" runat="server">

<asp:ScriptManager ID="ScriptManager1" runat="server" />

<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<br />
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
<br />
<br />
<br />
<asp:Button ID="ButtonPostBack" runat="server" Text="PostBack" />
<br />
<br />
</ContentTemplate>
</asp:UpdatePanel
</form>

</body>
</html>

After 3+ days of brainstorming, testing, debugging and everything I could throw at ASP.NET I have found a solution.

Theproblem lies not within ViewState, not with ASP.NET's Control Tree (nottechnically), not within the Code itself but in how ASP.NET handlesdynamic Controls in regards to their ID's.

If I modify my codeabove as demonstrated below everything works just fine. You wouldthink that incrementing the ID's instead of assinging the same ID's tothe same Controls would do nothing but for some bizarre reason thatshow it works.

My problem in my real Application is very similiarto this problem and I have in fact solved my problem. Its funny how ifI had been able to pin-point this problem several days ago I would beway beyond this. Oh well, thats ASP.NET.

ASPX Page:
<%@. Page Language="VB" AutoEventWireup="true" CodeFile="Default.aspx.vb" Inherits="_Default" %
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
</head>
<body
<form id="form1" runat="server">

<asp:ScriptManager ID="ScriptManager1" runat="server" />

<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<br />
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
<br />
<br />
<br />
<asp:Button ID="ButtonPostBack" runat="server" Text="PostBack" />
<br />
<br />
</ContentTemplate>
</asp:UpdatePanel
</form>

</body>
</html
Code Behind:
Partial Class _Default
Inherits System.Web.UI.Page

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

' Clearing any previous text.
label1.text = ""

Dim counter As Integer = 0

' If its the first time loading the Page
If Not Page.IsPostBack Then
Page.Session.Add("AddButton1", "True")
Page.Session.Add("AddButton2", "True")
Page.Session.Add("AddButton3", "True")
Page.Session.Add("AddButton4", "True")
Page.Session.Add("AddButton5", "True")
Page.Session.Add("AddButton6", "True")
Page.Session.Add("AddButton7", "True")
Page.Session.Add("AddButton8", "True")

Page.Session.Add("RemovalTracker", "")

' Else the page is performing a PostBack
Else
label1.text = CStr(Page.Session.Item("RemovalTracker")

)
End If

'Dynamically creating the Buttons and then adding them to the Page / Form.

If CBool(Page.Session.Item("AddButton1")) = True Then
Dim button1 As New Button
button1.Text = "Button1"
button1.ID = counter.ToString
counter += 1
AddHandler button1.Click, AddressOf testSub
UpdatePanel1.ContentTemplateContainer.Controls.Add(button1)
End If

If CBool(Page.Session.Item("AddButton2")) = True Then
Dim button2 As New Button
button2.Text = "Button2"
button2.ID = counter.ToString
counter += 1
AddHandler button2.Click, AddressOf testSub
UpdatePanel1.ContentTemplateContainer.Controls.Add(button2)
End If

If CBool(Page.Session.Item("AddButton3")) = True Then
Dim button3 As New Button
button3.Text = "Button3"
button3.ID = counter.ToString
counter += 1
AddHandler button3.Click, AddressOf testSub
UpdatePanel1.ContentTemplateContainer.Controls.Add(button3)
End If

If CBool(Page.Session.Item("AddButton4")) = True Then
Dim button4 As New Button
button4.Text = "Button4"
button4.ID = counter.ToString
counter += 1
AddHandler button4.Click, AddressOf testSub
UpdatePanel1.ContentTemplateContainer.Controls.Add(button4)
End If

If CBool(Page.Session.Item("AddButton5")) = True Then
Dim button5 As New Button
button5.Text = "Button5"
button5.ID = counter.ToString
counter += 1
AddHandler button5.Click, AddressOf testSub
UpdatePanel1.ContentTemplateContainer.Controls.Add(button5)
End If

If CBool(Page.Session.Item("AddButton6")) = True Then
Dim button6 As New Button
button6.Text = "Button6"
button6.ID = counter.ToString
counter += 1
AddHandler button6.Click, AddressOf testSub
UpdatePanel1.ContentTemplateContainer.Controls.Add(button6)
End If

If CBool(Page.Session.Item("AddButton7")) = True Then
Dim button7 As New Button
button7.Text = "Button7"
button7.ID = counter.ToString
counter += 1
AddHandler button7.Click, AddressOf testSub
UpdatePanel1.ContentTemplateContainer.Controls.Add(button7)
End If

If CBool(Page.Session.Item("AddButton8")) = True Then
Dim button8 As New Button
button8.Text = "Button8"
button8.ID = counter.ToString
counter += 1
AddHandler button8.Click, AddressOf testSub
UpdatePanel1.ContentTemplateContainer.Controls.Add(button8)
End If

End Sub

Protected Sub testSub(ByVal sender As Object, ByVal e As System.EventArgs)

' Appending the Button Text to SessionState.
Page.Session.Item("RemovalTracker") = Page.Session.Item("RemovalTracker") & " - " & CType(sender, Button).Text

' Building the ID for the Session Item that needs to be modified.
Dim buttonToRemove As String
buttonToRemove = "Add" & CType(sender, Button).ID
Session.Item(buttonToRemove) = "False"

' Preventing the Buttom from Rendering - this is CRUCIAL to my demonstration.
CType(sender, Button).Visible = False

Page.Form.Controls.Remove(CType(sender, Button))

End Sub

Dynamic controls in Ajax UpdatePanel

I created a dynamic button and want to add the button click event as update panel trigger.
But does not work. Any idea ?
Thanks

String clientID;

protectedvoid Page_Init(object sender,EventArgs e)

{

Button btn =newButton();

btn.Text ="Write Hello";

btn.Click +=newEventHandler(Button1_Click);

Page.Form.Controls.Add(btn);

clientID = btn.ClientID;

}

protectedvoid Button1_Click(object sender,EventArgs e)

{

Label1.Text ="hello";

}

protectedvoid Page_PreRender(object sender,EventArgs e)

{

AsyncPostBackTrigger trigger =newAsyncPostBackTrigger();

trigger.ControlID = clientID;

trigger.EventName ="Click";

UpdatePanel1.Triggers.Add(trigger);

}

Try this instead of your code.

protected void Page_Load(object sender, EventArgs e)
{

Button btn = new Button();
btn.Text = "Write Hello";
btn.ID = "Button1";
btn.Click += new EventHandler(Button1_Click);
UpdatePanel1.ContentTemplateContainer.Controls.Add(btn);
//Page.Form.Controls.Add(btn);
// clientID = btn.ClientID;

AsyncPostBackTrigger trigger = new AsyncPostBackTrigger();
trigger.ControlID = "Button1";
trigger.EventName = "Click";
UpdatePanel1.Triggers.Add(trigger);

}
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = "hello";

}


This works. But actually what I want is : when click on the Button1, the the UpdatePanel1 will be hide and a UpdateProgress (with a loading image) will show until the loading complete. And the UpdatePanel1 will show again with some updated info.


Try this code. I dont think its a perfect way. I am using some hack mentioned in

http://dotnetslackers.com/community/blogs/simoneb/archive/2006/09/02/481.aspx

<%@. 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">
protected void Page_Load(object sender, EventArgs e)
{

Button btn = new Button();
btn.Text = "Write Hello";
btn.ID = "Button1";
btn.Click += new EventHandler(Button1_Click);
UpdatePanel1.ContentTemplateContainer.Controls.Add(btn);
//Page.Form.Controls.Add(btn);
// clientID = btn.ClientID;

AsyncPostBackTrigger trigger = new AsyncPostBackTrigger();
trigger.ControlID = "Button1";
trigger.EventName = "Click";
UpdatePanel1.Triggers.Add(trigger);
}
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = "hello";
System.Threading.Thread.Sleep(4000);
}
</script
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID=sc1 runat=server ScriptPath="ScriptLibrary"></asp:ScriptManager>
<div>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Label ID="Label1" runat="server"Text="Label"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdateProgressrunat=server AssociatedUpdatePanelID=Updatepanel1 ID=up1DynamicLayout=true DisplayAfter=4 >
<ProgressTemplate>
<table>
<tr>
<td>
Loading......
</td>
</tr>
<tr>
<td>
<img src="http://pics.10026.com/?src=" alt="image" />
</td>
</tr>
</table>
</ProgressTemplate>
</asp:UpdateProgress>
</div>
</form>
</body>
</html>
<script language=javascript>
Sys.Application.add_load(ApplicationLoadHandler)
function ApplicationLoadHandler(sender, args)
{
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(HidePanel);
Sys.WebForms.PageRequestManager.getInstance().add_pageLoading(ShowPanel);
}
function HidePanel(sender, args)
{
for (var j = sender._updatePanelIDs.length - 1; j >= 0; j--)
{
varupdatePanel =document.getElementById(sender._uniqueIDToClientID(sender._updatePanelIDs[j]));
var postbackElement = args.get_postBackElement();
if(updatePanel && updatePanel.contains(postbackElement)) {
updatePanel.style.visibility='hidden';
}
}
}
function ShowPanel(sender, args)
{
var updatedPanels = args.get_panelsUpdating();
for (var j = updatedPanels.length - 1; j >= 0; j--)
{
updatedPanels[j].style.visibility='visible';
}
}
</script>


Is it posible to put the button outside the UpdatePanel ?

UpdatePanel1.ContentTemplateContainer.Controls.Add(btn);

Because I would not want the button to be hide while 'Ajax'.

Thanks

Dynamic controls and Updatepanel

Hi,

First time poster here. (waves)

Here is my problem: Dynamically created LinkButtons within an Updatepanel don't seem to fire their Commands.
I have a few LinkButtons that are dynamically created within an UpdatePanel based on the contents of a TextBox. Everything renders as it should, only when I click on one of the LinkButtons, nothing happens. When I Debug, it the function the LinkButtons refer to (trough Command) never fires up. I suspect that this has something to do with the fact that CommandEventHandler is never actually registered because of the partial update. Is this correct? What are my options in this situation?

hello.

can you show us the code?


This is the code that is being used to generate the buttons:
foreach (XmlNode rowin rows){ LinkButton klantLink =new LinkButton(); klantLink.Text = row["NAME"].InnerText +", " + row["FIRSTNAME"].InnerText; klantLink.CommandArgument = row["K_CONTACT"].InnerText; klantLink.Command +=new CommandEventHandler(gezochteKlant_Click); searchDiv.Controls.Add(klantLink); searchDiv.Controls.Add(new LiteralControl("<br />") );}
searchDiv.Visible = true;
searchPanel.Update();
And this is the location in the html where the content is added:
<atlas:UpdatePanel ID="searchPanel" runat="server" Mode="Conditional"> <ContentTemplate> <div runat="server" id="searchDiv" visible="false"> </div> </ContentTemplate></atlas:UpdatePanel>

hello again.

question: where are you adding the controls, ie, in which event?


They are added trough the OnTextChanged of a textbox.

hello.

hum, not sure about what's happening.

i've built a small sample that adds a button during the load event and this works ok:

<%@. 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">
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);

LinkButton klantLink = new LinkButton();
klantLink.Text = "hello";
klantLink.CommandArgument = "test";
klantLink.Command += new CommandEventHandler(gezochteKlant_Click);

searchDiv.Controls.Add(klantLink);
searchDiv.Controls.Add(new LiteralControl("<br />"));

}

void gezochteKlant_Click(object sender, EventArgs args)
{
txt.Text = DateTime.Now.ToString();
}
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<atlas:ScriptManager runat="server" ID="manager" EnablePartialRendering="true" />

<atlas:UpdatePanel runat="server" id="panel">
<ContentTemplate>
<div runat="server" id="searchDiv" />
<asp:TextBox runat="server" id="txt" />
</ContentTemplate>
</atlas:UpdatePanel>
<hr />
<%= DateTime.Now.ToString() %>
</div>
</form>
</body>
</html>

maybe the problem is that you're only creating the button during the textchanged event; a click will fire another postback, but you won't the buttons won't be created since the text didn't change and this will not fire your event.


Thanks for the reply. I think the problem is that I create the controls directly in the function linked to the ontextchanged event.

hello.

that's what i was trynig to say. since you add them on the textchanged event, you must also add them on future postbacks or else the button will not exist. so, what i suggest is adding some sort of flag that will let you add the buttons during the load event of a postback operation.


Hi,

I am very badly stuck up at something.

I am also dynamically loading my user control in the Update panel. My User Control act as a ModalPopUp Extender. So what i am doing is , on the click on the button on my page I am showing a Modal PopUp which is a User Control with some buttons and a grid. Which is being loaded on some values passed from the Page. So what I have done is I am adding Dynamically that user Control on the Click event of the button on my Page.But when I click any button my User Control , the event associated with that button does not get fired. It just unloades the usecontrol and event related to the buttons on the User control are getting fired.. Please help and look into this matter..

The Code:

protectedvoid btnAddContent_Click(object sender,EventArgs e)

{

//AddContent1 is my User Control with ProposalID and SectionID are the Properties.. Place Holder is on my Page where I am placing my control.

AddContent

AddContent1 = (AddContent)Page.LoadControl("AddContent.ascx");

AddContent1.ProposalID = 44;

AddContent1.SectionID = 1;

PlaceHolderTest.Controls.Add(AddContent1);

Label lblAdd = (Label)(AddContent1.FindControl("lblAdd"));

lblAdd.Text =

"Add Content";Label lblSecQues = (Label)(AddContent1.FindControl("lblSecQues"));

lblSecQues.Text =

"Section:";

mpeAddContent.Show();

}

Thanks in Avance

Abhishek

Dynamic controls and problem with UpdateProgress

I dynamically create several LinkButtons, and attach enenthandler for command event, and assign it for triggering Updatepanel. It works, but UpdateProgress doesn't show. I tried to add static button and assign it to updatepanel for triggering, and in this case updateprogress works, so i guess that's everything ok with ajax.

This is code in aspx:

1<asp:PlaceHolder ID="phMenu" runat="server"></asp:PlaceHolder>2<asp:UpdateProgress ID="UpdateProgress1" AssociatedUpdatePanelID="UpdatePanel1" runat="server" DisplayAfter="10">3 <ProgressTemplate>4 <span style="color: #ff0066">5 loading... </span>6</ProgressTemplate>7</asp:UpdateProgress>89<asp:UpdatePanel ID="UpdatePanel1" runat="server" >10<ContentTemplate>11<table width="100%" cellpadding=2 cellspacing=0 border=0>12 <asp:Repeater ID="rptFeeds" runat="server" EnableViewState=false>13 <ItemTemplate>14 <tr>15 <td>16 ... some data from db...17 </td>18 </tr>19 </ItemTemplate>20 </asp:Repeater>21 </table></ContentTemplate>22</asp:UpdatePanel>

code-behind in void OnInit:

1foreach (Category catin list)2{3 Panel pnl =new Panel();4 pnl.ID ="menu_" + cat.Id.ToString() ;5 pnl.CssClass ="menu_item";67 LinkButton lb =new LinkButton();8 lb.CommandArgument = cat.Id.ToString();9 lb.Command +=new CommandEventHandler(Clicked);10 lb.ID="trigger_"+cat.Id.ToString();11 lb.Text = cat.Name;12 lb.CssClass ="menu_a";1314 AsyncPostBackTrigger trigger =new AsyncPostBackTrigger();15 trigger.ControlID ="trigger_" + cat.Id.ToString();16 trigger.EventName ="Command";17 UpdatePanel1.Triggers.Add(trigger);1819 pnl.Controls.Add(lb);20 phMenu.Controls.Add(pnl);21}2223protected void Clicked(object sender, CommandEventArgs e)24{25 ChangeCat(Convert.ToInt32(e.CommandArgument));26}

Can you see why UpdateProgess doesn't work?

Hi,hudo

I think it's a normal issue.

You can set the clientclick property of theDynamic controls to show the UpdateProgess.

Thanks


The problem is that the control you want to trigger the UpdateProgress control is not inside the UpdatePanel.

See my post here:http://smarx.com/posts/why-the-updateprogress-wont-display.aspx for an explanation of why that doesn't work.

Dynamic Control TextBox values not refreshed with example code

Ok, here is my situation. I have a dynamic TextBox that is added to the UpdatePanel. I need to be able to set the value of that textbox on the UpdatePanel refresh. I'm able to do that with Label control but not with the TextBox. Is that a known issue, is there a workaround? I assume i can use the standard input control possibly, but due to my project i have to use pre existing set of user controls which use TextBox. Any help is appriciated. The code is included below:

Short explanation of the example:

Example provides a link to refresh the UpdatePanel. On refresh two controls are added to the collection with specified value which is the Current time. One control is textbox and the other one is label. If you keep hitting refresh the value of the Label is changed while the value of the TextBox remains the same. Example output:test //5/11/2007 1:57:52 PM

Thanks!

<%@dotnet.itags.org. Page Language="C#" AutoEventWireup="true" %><html xmlns="http://www.w3.org/1999/xhtml"><head runat="server"> <title>Untitled Page</title></head><script runat="server"> protected void Page_Load(object sender, EventArgs e) { TextBox textBox = new TextBox(); textBox.Text = DateTime.Now.ToString(); Label label = new Label(); label.Text = DateTime.Now.ToString(); test.Controls.Clear(); test.Controls.Add(textBox); test.Controls.Add(label); }</script><script type="text/javascript"> function UpdateDialogControl(val) { var ctrl = $get('<%=DialogTrigger.ClientID%>'); ctrl.value = val; __doPostBack('<%=DialogTrigger.UniqueID%>',''); }</script><body> <form id="form1" runat="server"> <a href="javascript:UpdateDialogControl(1)">test</a> <asp:HiddenField runat="server" ID="DialogTrigger" /> <asp:ScriptManager ID="ScriptManager1" EnablePartialRendering="true" runat="server" /> <asp:UpdatePanel UpdateMode="Conditional" ID="CenterContentPanel" runat="server" RenderMode="Inline"> <Triggers> <asp:AsyncPostBackTrigger ControlID="DialogTrigger" /> </Triggers> <ContentTemplate> <asp:PlaceHolder runat="server" ID="test"></asp:PlaceHolder> </ContentTemplate> </asp:UpdatePanel> </form></body></html>

In Page_Load Event, Put all the statement into the !IsPostBack block.

if (!IsPostBack)
{
//all the code
}


Okay ... the controls are not displayed at all on the refresh.

Textbox's update their value based on the posted value from the previous request. So you're adding it, then its getting updated, overwriting your set value. Disabling ViewState will not affect this, since the value comes from the posted values collection, not viewstate.

Normally TextBox's are updated by the time you get to OnLoad, but since this TextBox didn't exist at that time, it isn't updated until AFTER OnLoad.

So -- heres what you do...

Add the TextBox in OnInit instead. Then in OnLoad, you can set the value to whatever you want, knowing full well that the posted value has already been loaded.

I recommend you follow the link to my blog and read about dynamic controls :)


Hi, thanks for the answer. However ... I do understand how ViewState works and that you need to add controls dynamically during or before OnInit event in order for them to keep track of viewstate. Your solution will indeed work for that specific example. I need an ability to remove all the controls and add completely new ones on refresh with values i specified.

Actually this specific problem is not related to ViewState at all. Its the POST state of the textbox that is in question here. Even if you turned off viewstate to the entire page this same solution would apply. Dynamically added controls can keep track of their own viewstate no matter when you add them to the tree (as long as its before SaveViewState, which is between PreRender and Render).

If what you want is to destroy all the existing controls and start with fresh ones, its ok to clear to the control tree and start a new one -- but you have to give the existing controls a chance to load their prior state first, so that they "consume" that data. So you would do this in Load, or in response to an event (like a click event, which would be raised after Load).


So you are saying i have to add old controls before load event then in OnLoad even clear the controls collection and add new elements with a values i specified? (in the example above i'm adding controls in the Onload event).

BTW, I did not have the same problem without UpdatePanel it seems like it is adding extra remember state feature ...

Thanks for replies btw.


Nm, UpdatePanel does behave like any other control. It is not related to any extra remember state feature ... I guess i never encountered problem when i needed to completely refresh controls and yes you are right I did it on the SelectedIndex changed event before which worked fine. Now i need to do it on UpdatePanel refresh and this is where i'm having issues.

Thanks for the post again. I indeed needed to rebind the form on the event. So in case of UpdatePanel it was the ValueChanged event for the hidden input control. Just like you told the viewstate is restored when form is bound on OnLoad event and then when i bind it second time i can put new values for the controls.

Thanks!