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

Wednesday, March 28, 2012

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 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 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 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!

Dynamic Control creation not persisting through PostBack

Hey guys,

I've done some searching on dynamic control creation in the forums, but none of them take me to an Atlas page. I'm trying to build a HR Notification form with some simple Atlas UpdatePanels. Basically, I want to dynamically add Labels and TextBoxes to this form. For instance, if you select 3 from the Number of Children DDL, I want 3 child forms to be created under it. I've been able to create the forms (at least theoretically, I just create "test" Labels right now). The problem I'm running into is being able to read from these dynamically created Controls.

When I submit the form as a regular PostBack, all of my created labels seem to be lost. I get null exceptions when I try to use FindControl. Here are some code snippets:

protected void ddlNumChildren_SelectedIndexChanged(object sender, EventArgs e) {int runNum = Convert.ToInt32(ddlNumChildren.SelectedValue.ToString());int count = 0;while (count < runNum) { Label text=new Label(); text.ID ="testLabel" + count; text.Text ="test"; phNumChildren.Controls.Add(text); count++; } }protected void btnSubmit_Click(object sender, EventArgs e) {int runNum = Convert.ToInt32(ddlNumChildren.SelectedValue.ToString());int count = 0;while (count < runNum) { Label lbltest = phNumChildren.FindControl("testLabel" + count)as Label; Response.Write(lbltest.Text); } }

I'm assuming I have to save this data before the postback, but I need a little help in how I can do this. Thanks for your time and any help you can provide.

The problem is that the controls do not exist when the page is recreated during postback. You have two options :
1) Recreate the page during the Init() event if you have atlas UpdatePanels or Page_Load() if not
2) try http://www.denisbauer.com/ASPNETControls.aspx
3) Write your own code to save all controls in ViewState and reload them during the Init() event

Dynamic Control creation and viewstate management (client to server)

Hi all,

I am new to AJAX and this is my first port.

In my requirement i need to create set of dynamic controls (multiple instances of a custom webcontrol) to do this i am following the below steps.

    I have a user control with update panel in itI have a button "Add" to add new instance.Hidden field count to check number of dynamic instances addedHidden field to keep track of dynamic id'sRemove button to remove the instanceHandle UpdatePanel Load event to load the previous instance of controls before the control renders
    I have custom web control which inherits the ASP:Table classI override CreateChildControls method to create controls setHidden field to maintain the disabled control ids

rendering dynamic controls and its viewstate is working fine.

I am facing problem here.

I have some business logic in which the if the user selects "Yes" as the option in a RadioButtonList i am disabling few controls in the dynamically rendered sets at clientside. How to I get the controls state in the CreateChildControl method to see what was the control state using the hidden field as i am not able to get the form Posted values at this time. (Note: I know that we can use the UniqueID of the hidden field, but this will not work here as the unique id will be still the control ID unique id will be different when it renders.

So i want to know how to manage the viewstate from client and server in this scenario?

I tried to put in words as simple as possible.

Thanks for the help

- Satish

Missed to add this

When user clicks on "Yes" radio button i am saving the control id in the hidden field where in server side i can see the value in the hidden field at the server side and load the control state (either enabled or disabled). i am having problem here on how to retain the control state from clientside to the server side when it renders.

Thanks

Satish

Dynamic ContentTemplate in the TabPanel

How can i create a dynamic ContentTemplate in the TabPanel control ?

I have the following source:

<asp:ScriptManager ID="scriptManMain" runat="server" EnablePartialRendering="true" />
<ajaxToolkit:TabContainer runat="server" ID="tabContainerMS" CssClass="ajax__tab_xp">
<ajaxToolkit:TabPanel runat="Server" ID="tabPanelMaster" HeaderText="Orders Due Today">
<ContentTemplate>
XXXXXXXXX
<ContentTemplate>
</ajaxToolkit:TabPanel>
</ajaxToolkit:TabContainer>

I wanna change the ContentTemplate dynamic by a file .cs on page_load or another function, how can i do that ?

Thank′s

You could use the dynamic population capabilities of the tabpanel control for this which allows you to populate the content of each tab when it is activated via a web service call. Check out the Dynamic* properties on the control.
AjaxControlToolkit.TabPanel tpHome = new AjaxControlToolkit.TabPanel();
tpHome.HeaderText = "Home";
tpHome.ContentTemplate = Page.LoadTemplate("Home.ascx");
tcDefault.Tabs.Add(tpHome);

where tcDefault is TabControl you want this tabPanel to add, so Page.LoadTemplate is the method you should use

Dynamic content paired with a popupControlextender

Hi folks,

I have implemented a popup control exteder which works great, however I have to populate the content of the popup at page load. I would like the content of the popup to be dynamically generated at the time the popup is called with a server callback, kind of a PopupControlExtender meets DynamicPopulateExtender. I guess what i'm looking for is just an indication of the complexity of this task, and perhaps a pointer in the right direction.

Cheers,

Howard

Hi,

Actually, PopupControl has this functionality built in... you can set the DynamicServicePath, DynamicServiceMethod, DynamicContextKey, and DynamicControlID properties of PopupControlExtender and it will fetch dynamic content before it's shown.

Thanks,
Ted

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 Animation

Hi threr;

I want create an show a dynamic animation(exactly like select tag window in this page) using AJAX Control Toolkit animation control. At frist, I dont know how can I create a dynamic animation. Second, I want to call the animation via an event instead of button click.

Hi nima_montazeri,

Check outthis post on how to dynamically create Animations. You can't cause an animation to be played in an event other than those it supports. There is a workaround you could try though. You can create a dynamic OnLoad animation in your event which will play as soon as your page is reloaded - you just have to be careful to clear it out before the next postback.

Thanks,
Ted

Dynamic AJAX loaded control with updatepanel problem.

Hi,

Hopefully someone can shed some light onto whether this can be done as I am not having much luck so far.

I have a page with an Update panel. On this page I have a button that through an asynchronous postback loads a usercontrol (lets call it A). The usercontrol that is loaded (A) also has an update panel and a button. When the button on the usercontrol (A) is clicked I want it to load another usercontrol (B) through ajax into the updatepanel.

So we have nested usercontrols and updatepanels - the page hosts Usercontrol A which hosts usercontrol B.

Loading the Usercontrol A is working without a problem and I am persisting the loaded control by use of viewstate and reloading the controls in the OnInit event.

However clicking the button on usercontrol A will not load the usercontrol (B). This is because the click event behind the button does not fire.

I would be grateful if anyone has tried this and found a way of making it work.

Thanks

Hi,

Can you post a simple and clear sample here?


Hi, nzwy1p

Since you dynamically add the first(parent) user control, you should add it to the PlaceHolder in the Page_Load event every time instead of adding it just in theButton's Click event. Because when you only add it in theButton's Click event, after post back, theuser controlwill disappear. And itdoesn't land on your breakpoint inButton1_Click inUserControlA.ascx,There is non UserControlA when your postback by clickingButton1 in theUserControlA.

Try this:

Page:

<%@. 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 Button1_Click(object sender, EventArgs e)
{
UpdatePanel1.Update();
}

protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
UserControl uc;
uc = (UserControl)LoadControl("UserControlA.ascx");
PlaceHolder1.Controls.Add(uc);
}
}
</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>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Button1" />
</Triggers>
</asp:UpdatePanel>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" /></div>
</form>
</body>
</html>

UserControlA:

<%@. Control Language="C#" ClassName="UserControlA" %>

<script runat="server">
protected void Button1_Click(object sender, EventArgs e)
{
UserControl uc;
uc = (UserControl)LoadControl("UserControlB.ascx");
PlaceHolder1.Controls.Add(uc);
}
</script>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Button1" />
</Triggers>
</asp:UpdatePanel>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button in UserContorlB" />

UserControlB:

<%@. Control Language="C#" ClassName="UserControlB" %>

<script runat="server">

</script>

<asp:Label ID="Label1" runat="server" Text="UserContorlB's content"></asp:Label>

For more help, You can see theselink:http://forums.asp.net/t/1108394.aspx

Let me know if you need more info

Monday, March 26, 2012

Dynacly add scriptmanager when needed?

Hi,

I'm trying to create a Web User Control that uses asp.net Ajax. I'd like it to find out if a scriptmanager already exists in the page and, if not, add ti dynamically. Would such a thing be possible?


Thanks in advance for any help.


Regards,

Stefan

Yes its possible, you can check if ScriptManager is registered. FindControl(); or you can added it in the Master Page

http://forums.asp.net/thread/1441992.aspx

http://forums.asp.net/thread/1436775.aspx


Thanks for your quick reply. But how would I use FindControl if I don't know what the name of the scriptmanager would be?

I'm thinking of a situation where my control gets used in combination with other ajax controls, or gets used multpile times on a form. (Actually, my control would be a DotNetNuke module)

Any ideas?


If you didn't change it ScriptManager1


I know, but the hard thing is, that all controls get added to the page dynamically by DotNetNuke. This means I'm pretty sure the name won't be ScriptManager1...

So if there's no other way than to use findcontrol, the only option would be to add the ScripManager to the page itself somehow.


Thanks for your help.



hello.

you can get a reference to the ScriptManager control by using the static GetCurret method. If there's already a ScriptManager on the page, you will get a non null value.

I've put together an example ofUsing Control Adapters to automatically attach AJAX Extenders to ASP.NET Controls, which isn't exactly what you want, but there is code for walking through the controls on a page to see if there is already a ScriptManager or ScriptManagerProxy ...

http://damianblog.com/2006/11/16/adapters-and-extenders/

Damian


hello.

hum...why are you going through a cicle to get the scriptmanager control?


Because I'm doing it from an HttpModule ... and also because I didn't know of the static method :-)

Not sure if it will work in the module though ... will have a go.

Damian


hello.

well, i guess it might not work if you haven't instantiated the master page (which is easily solved by just "touching" the property)


Hi again, it's been a while since I had time to figure this thing out, but your answers look promising. Thanks a lot so far.

Dydfunctional behavior of the control HoverMeuExtender

Hi

With the ajax control HoverMenuExtender
i have a problem.


After have launch the page in Internet Explorer
with the onmouseover event on the linkbutton (as opportunely setted)
appears the popup.


The dydfunctional behavior is that
justlaunch the page,
little moments after than it opens the tab,
all the popups relative at the controls HoverMeuExtender
they open for some moments and then they close.
The effect isunpleasant.

Happen at you too?

Here are some sample codes about ajax:HoverMenuExtender for your reference.
<div>
<ul>
<li>
<asp:LinkButton runat="server" id="lnkParent" text="Parent Menu Item"/>
</li>
<asp:panel runat="server" id="pnlChild">
<ul>
<li>Child Item 1</li>
<li>Child Item 2</li>
</ul>
</asp:panel>
<ajax:HoverMenuExtender ID="hoverMenu"
PopupControlID="pnlChild"
TargetControlID="lnkParent"
PopupPosition="Bottom"
runat="server" />
</ul>
</div>
Wish the above can help you.

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.

Duplicate use of ID for AtlasControlToolkit.PopupControlBehavior

Hi, Im Using April CTP with AtlasControlToolkit-PopupControl

Whenever I use the control specified in the TargetControlID of the PopupControlExtender properties and place it inside a Updatepanel I get this error: Duplicate use of ID for AtlasControlToolkit.PopupControlBehavior

or in other words I would like to update the textbox from somewhere else using a Updatepanel.

<

atlas:UpdatePanelID="UpdatePane12"runat="server"Mode="Conditional"><Triggers><atlas:ControlEventTriggerControlID="DropDownList5"EventName="SelectedIndexChanged"/></Triggers><ContentTemplate><asp:TextBoxID="TextBoxDateFrom"runat="server"></asp:TextBox></ContentTemplate></atlas:UpdatePanel><asp:Panelrunat="server"ID="Panel1"CssClass="popupControl"><atlas:UpdatePanelID="UpdatePanel1"runat="server"><ContentTemplate><atlasToolkit:PopupControlExtenderID="PopupControlExtender1"runat="server"><atlasToolkit:PopupControlPropertiesTargetControlID="TextBoxDateFrom"PopupControlID="Panel1"Position="Bottom"/></atlasToolkit:PopupControlExtender><center><asp:CalendarID="Calendar1"runat="server"OnSelectionChanged="Calendar1_SelectionChanged"DayNameFormat="Shortest"BorderColor="#cccccc"BorderStyle="Solid"Width="180px"BackColor="White"><TodayDayStyleBackColor="#cccccc"/><DayStyleBackColor="Transparent"/><SelectedDayStyleFont-Bold="False"BackColor="IndianRed"/><WeekendDayStyleBackColor="#FFFFCC"/><TitleStyleBackColor="#5d7b9d"BorderColor="Black"Font-Bold="True"ForeColor="White"/></asp:Calendar></center></ContentTemplate></atlas:UpdatePanel></asp:Panel>

This is a known Atlas issue with the April CTP. I believe you'll find a work around for this in this thread:

http://forums.asp.net/thread/1282330.aspx

Dual slider control in asp.net

I have downloaded the sample code fro Dual slider control from

Computer http://www.dimebrain.com/2007/11/another-dual-sl.html

it works well in normal scenario. if i apply inside a <td> tag inside a<table> tag The sample code doesnt work

any idea?

You have

<table>

<tr>

<td>...</td>

</tr>

</table>

right?

If you miss the <tr> element then you have a "little" problem.


I cant understand can u tell in detail.

I am using <table><tr><td>...... </td></tr></table> tag.


The solution is i have to adjust the style property of the particular div tag. I solved my previous problem.

Now an another one issue is, This slider doesnt support the Update control of atlas. Y? What s d solution?

DropShadowExtender; Showing up on Top

I am using VS2008 and the included AJAX Control ToolKit

I have a master page that includes the scriptmanager and a panel with the DropShadowExtender

I have added a content page, that has a panel with a DropShadowExtender.

When the page displays, the 2nd DropShadow, goes UP, and displays on the top of the box. Basically an UPShadowExtender.

Any ideas to correct?

I have noticed a similar situation in the past if I am using tables or panels (and I would presume divs as well since panels are rendered as divs) I am trying to recall exactly what solved the issue but I do recall it had something to do with the width of each of the elements. I beleive if I had a table and had the extender to another control within that table, and the content in that table forced the outter table (or panel) to expand, I noticed that the dropshadow extender would push upwards.

Basically, what Im trying to say is, check your table, div, panel widths and heights. Make sure the content has ample room.


Hi,

Thank you for your post!

Create a simple repro for this issue if you can,and please post up the whole code of the repro.

Anyway, I agree withjgilmore. you should do moretroubleshoot wok and then you can provide us with more valuable information.

Best Regards,