Showing posts with label dynamically. Show all posts
Showing posts with label dynamically. Show all posts

Wednesday, March 28, 2012

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 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 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 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 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 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 content for modal popup

Hi -

I want to change the contents of a modal popup dynamically through client side script. For that purpose, I've included a div element and change it's innerhtml property. When I test whether the change got done I can read the new value through javascript but the modal popup extender shows the old html (which loaded when the page was loaded). I think I may have to call a method to let the modal popup extender know I updated the content, but I don't know how to do that.

Any help is greatly appreciated!!

Oliver

I thought I'd add some code so you know what I am talking about.

Thanks,

Oliver

 function showpopup() { event.bubble = false; var d = document.getElementById("popupcontent"); d.innerhtml='<img src="images/spinner.gif" alt="Please wait ..." />'; var popup =$find('BMPNoShow'); popup.show(); alert(d.innerhtml); }<ajaxToolkit:ModalPopupExtender ID="MPNoShow" BehaviorID="BMPNoShow" runat="server" CancelControlID="BNoShowCancel" DropShadow="true" PopupControlID="PNoShow" PopupDragHandleControlID="PNoShow" TargetControlID="PNoShow"> </ajaxToolkit:ModalPopupExtender> <asp:Panel ID="PNoShow" runat="server" Style="background: white; border-color: Gray; border-style: solid; width: auto; padding: 10px" EnableViewState="false"> <div id="popupcontent"> </div> <br /> <asp:Button ID="BNoShowCancel" runat="server" Text="Cancel" UseSubmitBehavior="false" /> <asp:Button ID="BNoShowConfirm" runat="server" Text="Mark as no-show" UseSubmitBehavior="false" /> <asp:HiddenField ID="HFNoShowRequest" runat="server" /> </asp:Panel>

Take a look at the Dynamic* properties of the modalpopup, which allow you to load the content of a modalpopup dynamically using a web service. This will automatically load the content into the modalpopup when it is shown without you having to do anything.


Thanks - that's even better than what I was trying to do :)

Dynamic CollapsiblePanels

I was wondering if anyone has ever dynamically added CollapsiblePanels to a web form based on data from a database? Do I need to create a separate instance for each panel area I need or can I do it with one CollapsiblePanel control? Basically what I am looking to do is create something like the following:

TITLE1
>FIELD1
>FIELD2

TITLE2
>FIELD3
>FIELD4
>FIELD5

All data is being pulled from a database so, the fields are added to a Panel based on the title they are associated with. My workflow is currently to:

1) Query the database to get the information
2) Loop through the records to add controls to a new content panel
3) When all of the fields have been added to the contents panel, create a new CollapsiblePanel control and add it to the form
4) Loop until there aren't any more groups

This seems to kind of work but I continue to get an error stating that I have two or more controls with the same ID. I believe I have traced this to the adding of the multiple CollapsiblePanels. I am generating a random number to assign to the CollapsiblePanel every time one is generated but, the error still happens.

Any ideas what could be going on here?


I was in the same situation and came up with the following code. I hope it helps. I use Patterns and Practices (v3.0) so use your method of choice to obtain the data. I make use of a place holder to dump the controls so make sure you put one on your form and call it plcHolderForPanels for this example. Good luck :)

using System;
using System.Data;
using System.Configuration;
using System.Text;
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;
using Microsoft.Practices.EnterpriseLibrary.Data;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
string sql = "SELECT * FROM [topics]";

// Get the topics
IDataReader reader = DatabaseFactory.CreateDatabase().ExecuteReader(CommandType.Text, sql);

// Display the topics
while (reader.Read())
{
GeneratePanels(reader["id"].ToString(), reader["name"].ToString());
}
}
}

private void GeneratePanels(string topicId, string topicName)
{
// 1. Create hte panel for the title
Panel pnlTitle = new Panel();
pnlTitle.ID = @."pnlTitle" + topicId;
pnlTitle.CssClass = "collapsePanelHeader";

Image imgTitle = new Image();
imgTitle.ID = @."imgTitle" + topicId;
imgTitle.ImageUrl = @."images/expand.jpg";

Label lblTitle = new Label();
lblTitle.ID = @."lblTitle" + topicId;
lblTitle.Text = " -- Click here to expand...";

pnlTitle.Controls.Add(imgTitle);
pnlTitle.Controls.Add(new LiteralControl(topicName));
pnlTitle.Controls.Add(lblTitle);

// 2. Create the content panel
Panel pnlContent = new Panel();
pnlContent.ID = @."pnlContent" + topicId;
pnlContent.CssClass = @."collapsePanel";

pnlContent.Controls.Add(new LiteralControl("This is some text..."));

// 3. Now create the collapsible panel control
AjaxControlToolkit.CollapsiblePanelExtender cpe = new AjaxControlToolkit.CollapsiblePanelExtender();
cpe.ID = @."cp" + topicId;
cpe.TargetControlID = pnlContent.ID;
cpe.ExpandControlID = pnlTitle.ID;
cpe.CollapseControlID = pnlTitle.ID;
cpe.Collapsed = true;
cpe.TextLabelID = lblTitle.ID;
cpe.ImageControlID = imgTitle.ID;
cpe.CollapsedImage = "images/expand.jpg";
cpe.ExpandedImage = "images/collapse.jpg";
cpe.SuppressPostBack = true;

plcHolderForPanels.Controls.Add(cpe);
plcHolderForPanels.Controls.Add(pnlTitle);
plcHolderForPanels.Controls.Add(pnlContent);
plcHolderForPanels.Controls.Add(new LiteralControl("<BR><BR>"));
}
}

Dynamic CollapsiblePanel

I am surely a novice, but was wondering if it is possible to dynamically build a page of collapsible panels based on the values in a SQL table. The code size would be greatly reduced if it can be done.Just another forum that noone uses!

I'll be honest, this is a very vague question. And it seems as though you are fishing for free code. We aren't here to code projects for you. If you are looking for pointers, I'll gladly provide this.

The approach I would take is to use either a SqlDataSource or ObjectDataSource to retrieve the data. I like working with objects, so it tends to take more code up front to get the data from SQL and turn it into objects in my object model. But once done, I then use the ObjectDataSource to get the data ready for binding.

Then you can use any number of databound controls. One example might be the Repeater control. This is a very free form control that will let you provide any HTML per object (or row) returned from the datasource. In the ItemTemplate, you just define the CollapsiblePanelExtender as you would in any databound control.

If you get stuck, please post here with the code that is blocking you and I'll do what I can to help.


Got it working. The problem was with the page sub-class.

Dynamic Collapsible Panels - Flicker and slow load

Hello,

I have a User Control that dynamically creates several collapsible panels depending on records read from sql db. The panels are created okay, but the page loads slow and flickers several times. It partially loads, displays first panel very quickly and goes blank until all other panels are created and data is loaded. It looks awfull!!

Is there a way to improve the UI?, so the page shows all panels when loaded. It would be good also showing a "wait for a moment" message when creating many panels. What is the best way to do it?

Thank you,

Carlos Lozano

Any one?

Any comments would be helpfull. Thank you.Carlos


I can't help with your issues, but could you show me how you create dynamic panels based on SQL data? Once I get it working, I will discuss with others around here to determine if there is a solution.


Mine works without the flickering. I don't use a code behind in the control that buildds it.


Try to set in web.config <compilation debug="false">

It will improve some performance.


Below is the main code that creates the panel.

Notes:

1) CustomPanel is a customization of Panel class.

2) sNewEndingID is a counter to identify each panel and its controls.

3) TableUtil.AddTableRow function basically adds the <tr><td>controls here</td></tr> to the panel to organize the panel presentation.

4) oOptions.getOptionData("Inspection") Pulls data from SQL DB to populate some of the control options (ie. DropdownList, etc).

-- Code --

public void createInspectorPanel(ref CustomPanel oParentPanel, string sNewEndingID)
{
OptionsObject oOptions = new OptionsObject();
//oParentPanel.Visible = false;

AjaxControlToolkit.CollapsiblePanelExtender oExPanel = new AjaxControlToolkit.CollapsiblePanelExtender();
CustomPanel oPanel = new CustomPanel();
oPanel.ID = "InspectorItem" + sNewEndingID;
if (oParentPanel.Controls.IndexOf(oPanel) == -1)
{
oExPanel.ID = "InspectorPanelExtender" + sNewEndingID;
oExPanel.TargetControlID = "InspectorPanel" + sNewEndingID;
oExPanel.ExpandControlID = "InspectorPanelHeader" + sNewEndingID;
oExPanel.CollapseControlID = "InspectorPanelHeader" + sNewEndingID;
oExPanel.Collapsed = true;
oExPanel.TextLabelID = "lblInspectorControlText" + sNewEndingID;
oExPanel.CollapsedText = sNewEndingID + ") - Click to view details ";
oExPanel.ExpandedText = sNewEndingID + ") - Click to hide details ";
oExPanel.SuppressPostBack = false;
oPanel.Controls.Add(oExPanel);

CustomPanel oPanelHeader = new CustomPanel();
oPanelHeader.ID = "InspectorPanelHeader" + sNewEndingID;
oPanelHeader.CssClass = "collapsePanelHeader";
//oPanelHeader.Width = 300;
oPanelHeader.Width = Unit.Percentage(98);

Label oCounterLabel = new Label();
oCounterLabel.ID = "lblInspectorCounter" + sNewEndingID;
oPanelHeader.Controls.Add(oCounterLabel);

Label oControlLabel = new Label();
oControlLabel.ID = "lblInspectorControlText" + sNewEndingID;
oControlLabel.CssClass = "BTextClass";
oPanelHeader.Controls.Add(oControlLabel);
oPanel.Controls.Add(oPanelHeader);

CustomPanel oDetailPanel = new CustomPanel();
oDetailPanel.ID = "InspectorPanel" + sNewEndingID;
oDetailPanel.Height = 50;
//oDetailPanel.Width = 350;
oDetailPanel.Width = Unit.Percentage(98);

HtmlTable oTable = new HtmlTable();
TableUtil.AddTableRow(ref oTable, 1, "InspectorName", "Name: ", 1, sNewEndingID);
TableUtil.AddTableRow(ref oTable, 2, "CompanyName", "Company: ", 1, sNewEndingID);
DropDownList MPICertLevel = new DropDownList();
TableUtil.AddTableRow(ref oTable, ref MPICertLevel, ";1;2;3", "MPICertLevel", "MPI Cert. Level: ", sNewEndingID);
DropDownList LPCertLevel = new DropDownList();
TableUtil.AddTableRow(ref oTable, ref LPCertLevel, ";1;2;3", "LPCertLevel", "LP Cert. Level: ", sNewEndingID);
DropDownList EMICertLevel = new DropDownList();
TableUtil.AddTableRow(ref oTable, ref EMICertLevel, ";1;2;3", "EMICertLevel", "EMI Cert. Level: ", sNewEndingID);
DropDownList UTCertLevel = new DropDownList();
TableUtil.AddTableRow(ref oTable, ref UTCertLevel, ";1;2;3", "UTCertLevel", "UT Cert. Level: ", sNewEndingID);
//DropDownList Inspection = new DropDownList();
ListBox Inspection = new ListBox();
Inspection.DataTextField = "Description";
Inspection.DataValueField = "Id";
Inspection.DataSource = oOptions.getOptionData("Inspection");
Inspection.Rows = 6;
Inspection.SelectionMode = ListSelectionMode.Multiple;
Inspection.DataBind();
TableUtil.AddTableRow(ref oTable, ref Inspection, "Inspection", "Inspections Done: ", sNewEndingID);
DropDownList TxtPerformance = new DropDownList();
TxtPerformance.DataTextField = "Description";
TxtPerformance.DataValueField = "Id";
TxtPerformance.DataSource = oOptions.getOptionData("InspPerformance");
TxtPerformance.DataBind();
TableUtil.AddTableRow(ref oTable, ref TxtPerformance, "Performance", "Performance: ", sNewEndingID);
TableUtil.AddTableRow(ref oTable, 9, "InspDiscrepancies", "Discrepancies: ", 2, sNewEndingID, 40);

oDetailPanel.Controls.Add(oTable);
oPanel.Controls.Add(oDetailPanel);
oParentPanel.Controls.Add(oPanel);
//oParentPanel.Visible = true;
}
}


Did you set your Content Panel's height to 0px. I'm not sure if I'm reading this correctly but I seeoDetailPanel.Height = 50;Maybe try setting that to 0 and see if that helps with the flickering.

Dynamic Cascading DropDownLists

Hi All,

Thx, for your help in advance. I have 2 update panels, UpdatePanel1 and UpdatePanel2 respectively.

UpdatePanel1 has 'n' dynamically generated DropDownLists with their CascadingDropDown extender.

UpdatePanel2 has a TextBox and a Button.

When the last dynamically generated dropdownlist is clicked (a selectedIndexChanged event is fired) where I clear the TextBox. Since they are dynamically generated, I always add the dynamic dropdownlists (and extenders) on the OnInit event of the page. My problem is that when the Button is clicked, the DropDownLists may be still loading their values (some default selected values, selected via cascadingDropDown.SelectedValue property), so on postback the SelectedIndexChanged event is fired, before the OnClick event of the button takes place. This causes the following scenario:


1. DropDownLists Dynamically Added

2. User Enters Text (DropDownLists StillLoading their default values)

3. User Clicks Button (DropDownLists StillLoading their default values)

4. SelectedIndexChanged Fired (this clears the textbox , so I can't read the value in step 2)

5. Button's OnClick Fired

6. When I try to read the TextBox text, it has been cleared in step 4.

Am I doing something rong? Why both events(SelectedIndexChanged and OnClick) are fired when I'm expecting only the OnClick event to happen. Any thoughts of how to avoid this?


Thx




Hi Maxdmvp,

First, we suggest that you should set your UpdatePanel's UpdateMode="Conditional". This will avoid that one UpdatePanel cause to another UpdatePanel's refreshment.

maxdmvp:

4. SelectedIndexChanged Fired (this clears the textbox , so I can't read the value in step 2)

5. Button's OnClick Fired

You should use a debugging tool such as Web Development Helper and FireBug to find out the reason.

Best regards,

Jonathan


Thx for your response Jonathan...


The problem that I describe rises when you try to edit. Imagine this scenario: The dropDownList's (updatePanel1) are properties of a product, when you finish selecting you have assembled a product model number. When you enter the page to edit how many items of this product you want in your cart (textBox and button in UpdatePanel2), you already know the product's properties (you preselect the values in the dropDownList's), but while these are loading it is posible for you to enter a number in the textBox and click the "add" button in UpdatePanel2. In this scenario the "SelectedIndexChanged" is fired before the "OnClick" of the button, when I just expect the "OnClick" to be fired. As you can see it doesn't matter, in this case, if the UpdateMode="Conditional".

Also thx for your advice on user FireBug, I use it often but I'm not sure how can it help me debug this problem... could you please provide a further advice?

Thx



Hi Maxdmvp,

I'm not clear enough now, so would you please give me a sample now? Please do me a favor that remove all the unnecessary part before you post it. Thanks.

Best regards,

Jonathan.

Dynamic AutoCompleteExtenders -- 0 Requests Made

I'm dynamically creating a set of textboxes with autocompleteextenders, but something's not going quite right. Here's the code:

FilterList.Controls.Clear(); Table FiltersTable =new Table(); FilterList.Controls.Add(FiltersTable);foreach (string Filterin _Columns) { TableRow FilterRow =new TableRow(); TableCell LabelCell =new TableCell(); Label ColumnName =new Label(); ColumnName.Text = Filter +":"; LabelCell.Controls.Add(ColumnName); TableCell TextCell =new TableCell(); TextBox ColumnText =new TextBox(); ColumnText.ID = Filter +"Box"; ColumnText.Width = 100; ColumnText.CssClass = Filter; TextCell.Controls.Add(ColumnText); AjaxControlToolkit.AutoCompleteExtender Extender =new AjaxControlToolkit.AutoCompleteExtender(); Extender.ID = Filter +"Extender"; Extender.TargetControlID = ColumnText.ID; Extender.ServicePath ="GetAutoCompleteItems.asmx"; Extender.ServiceMethod ="GetCompletionList"; Extender.MinimumPrefixLength = 2; Extender.CompletionInterval = 500; Extender.CompletionSetCount = 10; Extender.ContextKey = Filter; TextCell.Controls.Add(Extender); FilterRow.Cells.Add(LabelCell); FilterRow.Cells.Add(TextCell); FiltersTable.Rows.Add(FilterRow); }

I brought up Firefox/Firebug and watched the network requests. I'd clear out the list of current requests so it was completely empty. As soon as I typed 2 characters into one of the textboxes, firebug would pop up "0 requests". And of course my web service is never hit.

Any ideas on what I might be doing wrong?

I'm still trying to figure this out. Has anyone had any success dynamically adding AutoCompleteExtenders to a page?

Edit: After more searching, it appears the answer fromthis page works.

Dynamic AnimationTarget

I have a question concerning animation, specifically the AnimationTarget property. Has anyone found a way to changethis property dynamically? Meaningt I have a lot of animations that will be the exact same for a lot of different controls, and I do not want a lot of repeat code with just the AnimationTarget that changes. Thanks for any help.

Eric

Hi,

In your markup , change AnimationTarget to be AnimationTargetScript. Then it will be dynamically evaluated on the client side , each time the animation runs .

Ex :

<Resize Height="100" Width="100" AnimationTargetScript="GetID()" />

function GetID() {

return ControlID;
}

Hope this helps


Hmm, I dont think I understand. I tried that and I just put an alert in my javascript to make sure it goes into the function, but nothing happens. Any help would be appreciated.

hi,

Can you share your markup ?


Here is my animation code:

<ajaxToolkit:AnimationExtender id="MyExtender"
runat="server" TargetControlID="LinkButton1">
<Animations>
<OnClick>
<Sequence>
<EnableAction Enabled="false" />
<Color AnimationTarget="cell1"
Duration="0"
StartValue="#FF0000"
EndValue="#FF0000"
Property="style"
PropertyKey="backgroundColor" />
<Color AnimationTarget="cell1"
Duration="0"
StartValue="#000000"
EndValue="#000000"
Property="style"
PropertyKey="color" />
<EnableAction Enabled="true" />
</Sequence>
</OnClick>
</Animations>
</ajaxToolkit:AnimationExtender>

and here is my javascript
<script language=javascript>
function getID()
{
alert(document.getElementById('MyExtender').id);
return document.getElementById('MyExtender').id;
}
</script


im sorry it should be this code
<ajaxToolkit:AnimationExtender id="MyExtender"
runat="server" TargetControlID="LinkButton1">
<Animations>
<OnClick>
<Sequence>
<EnableAction Enabled="false" />
<Color AnimationTargetScript="getID()"
Duration="0"
StartValue="#FF0000"
EndValue="#FF0000"
Property="style"
PropertyKey="backgroundColor" />
<Color AnimationTargetScript="getID()"
Duration="0"
StartValue="#000000"
EndValue="#000000"
Property="style"
PropertyKey="color" />
<EnableAction Enabled="true" />
</Sequence>
</OnClick>
</Animations>
</ajaxToolkit:AnimationExtender>


hi ,

The issue is that from your GetID() function , you have to return the TargetControlID that you want to be animated , not the ID of the AnimationExtender itself.

so . if you were animating button1 . your GetID() function would be

function GetID() {

return '<%Buttin1.ClientID%>';

}

Hope this helps clear it up


shouldnt my function at least alert though? it is like it doesnt even call the function


hi,

instead of

alert(document.getElementById('MyExtender').id);

try

alert('I am running');

if there is an error in the code , alert will not fire

Dynamic Ajax Tab Container raises unhandled exception: Specified argument was out of the r

Hi -

I've a problem with the ajax tab container: I try to add additional ajax tab panels dynamically at run time. This works fine, but as soon as I do it, any button I click on the page throws the exception below.

So, if I comment these 2 lines out:

Dim tpAsNew AjaxControlToolkit.TabPanel

Me.TCSpecialties.Tabs.Add(tp)

everything works fine (TCSpecialties is a Tab Container). Once I leave them in, this exception is thrown:

Specified argument was out of the range of valid values.
Parameter name: value

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.ArgumentOutOfRangeException: Specified argument was out of the range of valid values.
Parameter name: value

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.


Stack Trace:

[ArgumentOutOfRangeException: Specified argument was out of the range of valid values.Parameter name: value] AjaxControlToolkit.TabContainer.set_ActiveTabIndex(Int32 value) +381 AjaxControlToolkit.TabContainer.LoadClientState(String clientState) +160 AjaxControlToolkit.ScriptControlBase.LoadPostData(String postDataKey, NameValueCollection postCollection) +73 AjaxControlToolkit.TabContainer.LoadPostData(String postDataKey, NameValueCollection postCollection) +32 AjaxControlToolkit.ScriptControlBase.System.Web.UI.IPostBackDataHandler.LoadPostData(String postDataKey, NameValueCollection postCollection) +11 System.Web.UI.Page.ProcessPostData(NameValueCollection postData, Boolean fBeforeLoad) +718 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3776

Does anyone have a clue as to what may be going on??

Any help highly appreciated

I think you need to set the activetab which is null

somthing like TCSpecialties.ActiveTab = tp

This will set the active tab to the newly added tab.


I did that - still the same behavior as before. The tabs get displayed correctly, as a matter of fact. Any ideas?


By "adding tabs dynamically at runtime" are you doing this client side or server side? Can you file a bug at codeplex at attach a simple repro?


I am doing this on the server side ... what I meant is that the controls are not dropped in the form at designtime but rather created based on database fields (one Tab per record, with 3 records in the database). Will try to create a repro


You may need to recreate the tab panels when the postback occurs in the Page_init because the tabpanels do not exist on post backs until they have been made...

So in Page_init you should call a function that makes the default tab collection and then later on the page you can add a new tab panel to the collection.

Hope this makes sense.


That fixed itSmile

Thanks very much!!!!

Oliver


Thanks guys for the thread. It has saved us HEAPS of time.

After reading it though I still had a few problems getting it to work (which it is now).
These are probably pretty obvious to most of you out there, but it may be helpful for those reading this thread that still can't get it working.

We are now creating the tabbed panels dynamically in Page_Init as instructed.
One thing we did wrong was to only do this if it was not a postback. In hindsight we obviously we needed to do this all the time.

Also for those who are wondering how to save the selected values on the page if you are recreating the tab panels everytime, I think that the save view state and load view state events are doing this for you automatically; I think they just need to have the controls created (which you are now doing in page_init) and then they will do the rest.

Isn't life grand :)

Thanks again for sharing this info with everyone.

Mark


Can you please post a code example here of what must be written inside the page_init function ?


Just create whatever dynamic controls you have. If you add a text box with the ID="tb1" dynamically (I know, it's more likely you created something data driven), just add the following

dim l as new textbox

l.id="tb1"

me.page.controls.add(l)

That's it. Just do this for any controls you added. Note: Do not reset the values, viewstate will take care of that for you.

Now, you can simply access the text property somewhere else in your code behind as

l.text

and it will have the text the user entered. Hope that helps


Hello,

I am doing it according to this post but still getting "Index out of range" exception when I try to add a second TabPanel by clicking a button...

Any ideas?...

public partial class TestPage : System.Web.UI.Page
{
private TabContainer _tabContainer;

protected void Page_Init(object sender, EventArgs e)
{
_tabContainer = new TabContainer();
_tabContainer.Height = Unit.Pixel(250);

TabPanel tab = new TabPanel();
tab.HeaderText = "New Tab 1";

_tabContainer.Tabs.Add(tab);

tab = new TabPanel();
tab.HeaderText = "New Tab 2";

_tabContainer.Tabs.Add(tab);
_tabContainer.ActiveTab = tab;

ContainerPanel.Controls.Add(_tabContainer);
}
protected void Button1_AddTab(object sender, EventArgs e)
{
TabPanel tab = new TabPanel();
tab.HeaderText = "New Tab 3";

_tabContainer.Tabs.Add(tab);
_tabContainer.ActiveTab = tab;
}
}


Hey can you clarify the sentence:

"

So in Page_init you should call a function that makes the default tab collection and then later on the page you can add a new tab panel to the collection."

What's a default tab collection? I'm having the same problem and I don't really understand the solution.

Thanks


I can't really clarify better than I did before... Just look at the code I posted and you'll understand...

Thanks,

David


Can some please explain what is the reason behind this error?

Is it a feature or a bug?

I thank all for the answers, but eventually they either unclear or imply that if I want to add tabs dynamically then I have to create all the other controls on page dynamically (which seems to me somehow unpractical if I have a control rich page).

Any ideas?


This is what I found as a solution to this mess.

Assume you have a TabContainer with a TabPanel at design time. You also have a button which when clicked adds a new TabPanel to the TabContainer at runtime.

On postback, every TabPanel already added dynamically must be recreated before the Button_Click and the Page_Load are processed. In other words, this applies to all TabPanels except for the first one. This can be done in the Page_Init handler which I do not recommend for a very good reason: As soon as you mess with it you have to recreateall other dynamic controls your page may contain!

On the other hand, the TabContainer control has an Init handler itself so why not use it insteadWink

The following example adds a new TabPanel every time the button is clicked. Each tab has a header "Tab X" where X = 1 ... tabIndexName. You also need the tabIndexName static member to keep count of how many TabPanels have been created so far. Last but not least, have in mind that you cannot use the ViewState object inside the Init method.

public partialclass TabContainerTest : System.Web.UI.Page
{
public static int tabIndexName;

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
tabIndexName = 2;
}
}

protected void Button1_Click(object sender, EventArgs e)
{
AjaxControlToolkit.TabPanel tab =new AjaxControlToolkit.TabPanel();
tab.HeaderText ="Tab " + Convert.ToString(tabIndexName++);
TabContainer1.Tabs.Add(tab);
}

protected void TabContainer1_Init(object sender, EventArgs e)
{
if (IsPostBack)
{
for (int i = 1; i < tabIndexName - 1; i++)
{
AjaxControlToolkit.TabPanel tab =new AjaxControlToolkit.TabPanel();
tab.HeaderText ="Tab " + Convert.ToString(i + 1);
TabContainer1.Tabs.Add(tab);
}
}
}
}

Hope this helps.

Monday, March 26, 2012

Dynamic Accordion Content

Is there a way to dynamically add to the Content of an AccordionPane?Has anyone been able to do this?

mdenn:

Is there a way to dynamically add to the Content of an AccordionPane?

A short sample:

<%@. Page Language="VB" AutoEventWireup="true" CodeFile="Default.aspx.vb" Inherits="_Default" %>
<%@. Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="act" %><!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 id="Head1" runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<ajax:ScriptManager runat="server" ID="sm1" EnablePartialRendering="true"></ajax:ScriptManager>
<act:Accordion runat="server" ID="Accordion1">
<Panes>
<act:AccordionPane runat="Server" ID="AccordionPane1" >
<Header>
<b>Pane one</b>
</Header>
<Content>
<asp:Panel runat="Server" ID="panel1">
Just some text here. <br />
</asp:Panel>
</Content>
</act:AccordionPane>
<act:AccordionPane runat="Server" ID="AccordionPane2">
<Header>
<b>Pane two</b>
</Header>
<Content>
<asp:Label ID="Label1" runat="server" Text="First label"></asp:Label><br /><br />
<asp:Label ID="Label2" runat="server" Text="Last label"></asp:Label>
</Content>
</act:AccordionPane>
</Panes>
</act:Accordion>
</form>
</body>
</html>
PartialClass _Default
Inherits System.Web.UI.Page

Protected Sub Page_Init(ByVal senderAs Object,ByVal eAs System.EventArgs)Handles Me.Init
If Not Page.IsPostBackThen
Dim tmpLabelAs New Label
tmpLabel.Text ="Programmatically added label."Dim tmppanelAs Panel
tmppanel =Me.Accordion1.Panes(0).FindControl("Panel1")
If Not tmppanelIs Nothing Then tmppanel.Controls.Add(tmpLabel)End If
End If
End Sub

End Class

 
For some reason, adding the control directly to AccordionPane1.Controls caused the whole Accordion to crash and burn (both panes would stay open, can't manipulate them).
Do I need to do it on the Page_Init event? I tried it on the onLoad for the Accordion, and that didn't seem to work.

mdenn:

Do I need to do it on the Page_Init event? I tried it on the onLoad for the Accordion, and that didn't seem to work.

Works fine in Page_Load for me. What kind of errors or unexpected behavior are you getting?


I found out my problem... I had copied the code from our old accordion control that called another page to get the data to fill in the Pane, and I forgot to take that out.

Dyanmically adding TabPanels in TabContainer Control

Hi,

I have added the TabContainer control in my page.

the problem is If i add TabPanel Dynamically in TabContainer, these TabPanels do not appera in rendered page.

But if i add one TabPanel at design time and then add other TabPanels dynamically then they appear in page.

I am using the ControlToolKit release in May.

Hi,

It's hard to tell why from your description. And I made a sample, please try it and compare it with your code.

protected void Page_Load(object sender, EventArgs e)
{

AjaxControlToolkit.TabPanel tbpanel = new AjaxControlToolkit.TabPanel();
tbpanel.HeaderText = "Tab 01";
tbpanel.Controls.Add(new TextBox());
Label lb = new Label();
lb.Text = "Content";
tbpanel.Controls.Add(lb);
TabContainer1.Tabs.Add(tbpanel);

}

Hope this helps.

dyanamic creation of toolkit controls?

Hi,

Can we create ajax controls dynamically i.e. in javascript? For example, I wish to create a tab control dynamically? Can we do that?

--jon

You can definitely create your AJAX controls/behaviors using the $create() statements (most likely called/hooked-up from the application init function). You should create a few Ajax controls declaratively in the page and then view the source it outputs to get an idea of the syntax needed.

Saturday, March 24, 2012

DropdownList OnSelectedIndexChanged event within ModalPopupExtender

I have aModalPopupExtender with two DropdownLists. I want to populate the second dropdownlist dynamically base on the user selection in the first dropdownlist. Once user selects values from both dropdown lists, then I want to postback the entire page.

But the OnSelectedIndexChanged event of the dropdownlist is not firing whenever the selection is changed.

Is this possible withinModalPopupExtender? Appreciate your help.

You may want AutoPostBack="true" and an UpdatePanel.