Showing posts with label updatepanel. Show all posts
Showing posts with label updatepanel. Show all posts

Wednesday, March 28, 2012

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 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 in Ajax UpdatePanel

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

String clientID;

protectedvoid Page_Init(object sender,EventArgs e)

{

Button btn =newButton();

btn.Text ="Write Hello";

btn.Click +=newEventHandler(Button1_Click);

Page.Form.Controls.Add(btn);

clientID = btn.ClientID;

}

protectedvoid Button1_Click(object sender,EventArgs e)

{

Label1.Text ="hello";

}

protectedvoid Page_PreRender(object sender,EventArgs e)

{

AsyncPostBackTrigger trigger =newAsyncPostBackTrigger();

trigger.ControlID = clientID;

trigger.EventName ="Click";

UpdatePanel1.Triggers.Add(trigger);

}

Try this instead of your code.

protected void Page_Load(object sender, EventArgs e)
{

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

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

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

}


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


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

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

<%@. Page Language="C#" %
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{

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

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


Is it posible to put the button outside the UpdatePanel ?

UpdatePanel1.ContentTemplateContainer.Controls.Add(btn);

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

Thanks

Dynamic controls and Updatepanel

Hi,

First time poster here. (waves)

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

hello.

can you show us the code?


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

hello again.

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


They are added trough the OnTextChanged of a textbox.

hello.

hum, not sure about what's happening.

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

<%@. Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);

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

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

}

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

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

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

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


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

hello.

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


Hi,

I am very badly stuck up at something.

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

The Code:

protectedvoid btnAddContent_Click(object sender,EventArgs e)

{

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

AddContent

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

AddContent1.ProposalID = 44;

AddContent1.SectionID = 1;

PlaceHolderTest.Controls.Add(AddContent1);

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

lblAdd.Text =

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

lblSecQues.Text =

"Section:";

mpeAddContent.Show();

}

Thanks in Avance

Abhishek

Dynamic controls and problem with UpdateProgress

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

This is code in aspx:

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

code-behind in void OnInit:

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

Can you see why UpdateProgess doesn't work?

Hi,hudo

I think it's a normal issue.

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

Thanks


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

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

Dynamic Control TextBox values not refreshed with example code

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

Short explanation of the example:

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

Thanks!

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

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

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


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

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

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

So -- heres what you do...

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

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


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

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

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


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

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

Thanks for replies btw.


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

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

Thanks!

Dynamic association between UpdatePanel and UpdateProgress not working

Hi,

I haven't really used the ASP.NET AJAX framework before and I'm trying to get this to work without any luck. On my page is a repeater control and in its itemtemplate I generate an UpdatePanel and an UpdateProgress control (and a couple of other items) along with a LinkButton. The UpdatePanel has another repeater inside it. The idea is when I click on of the LinkButtons, it binds a datasource to the innermost repeater and refreshes the associated UpdatePanel (the panel is set to Conditional updatemode). It all works well but the associated UpdateProgress doesn't show, ever.

I've tried declarative setting the AssociatedUpdatePanelID in my ASP.NET code and I've tried to set it programatically in the ItemDataBound property of the outermost repeater (I've tried setting it to ID, ClientID and UniqueID) with no luck. If I leave the AssociatedUpdatePanelID untouched it sort of work but the problem is that ALL UpdateProgress controlls are displayed when a LinkButton is pressed.

The following experimentation code is the one I've been trying to make it work
 <asp:scriptmanager id="ScriptManager1" runat="server"> </asp:scriptmanager> <asp:repeater id="rptAlternatives" runat="server" onitemcreated="rptAlternatives_ItemCreated" onitemdatabound="rptAlternatives_ItemDataBound"> <itemtemplate> <div style="border: 1px solid #000; width: 300px; height: 100px; margin: 10px 0 10px 0;"> <asp:linkbutton id="lnkToggleSementPanel" runat="server" text="Toggle segments"></asp:linkbutton> <asp:updateprogress id="progress" runat="server" AssociatedUpdatePanelID="updSegmentPanel"> <ProgressTemplate> Loading... </ProgressTemplate> </asp:updateprogress> <asp:updatepanel id="updSegmentPanel" runat="server" updatemode="Conditional"> <contenttemplate> <asp:repeater id="rptSegments" runat="server"> <headertemplate> <div style="background-color: red; width: 100%;"> </headertemplate> <itemtemplate><%# Container.DataItem%> </itemtemplate> <footertemplate> </div> </footertemplate> </asp:repeater> </contenttemplate> </asp:updatepanel> </div> </itemtemplate> </asp:repeater>

using System;
using System.Collections.Generic;
using System.Data;
using System.Configuration;
using System.Collections;
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
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
List<int> items =new List<int>();
for (int i = 0; i < 5; i++)
items.Add(i);

this.rptAlternatives.DataSource = items;
this.rptAlternatives.DataBind();
}
}
protected void rptAlternatives_ItemCreated(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
{
LinkButton lnkToggleSementPanel = e.Item.FindControl("lnkToggleSementPanel")as LinkButton;
if (lnkToggleSementPanel !=null)
{
lnkToggleSementPanel.Click +=new EventHandler(lnkToggleSementPanel_Click);
lnkToggleSementPanel.CommandArgument = e.Item.ItemIndex.ToString();
this.ScriptManager1.RegisterAsyncPostBackControl(lnkToggleSementPanel);
}
}
}

protected void rptAlternatives_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
{
UpdatePanel updSegmentPanel = e.Item.FindControl("updSegmentPanel")as UpdatePanel;
if (updSegmentPanel !=null)
{
UpdateProgress progress = e.Item.FindControl("progress")as UpdateProgress;
if (progress !=null)
{
progress.DisplayAfter = 0;

// NON OF THESE WORK!
//progress.AssociatedUpdatePanelID = updSegmentPanel.ClientID;
//progress.AssociatedUpdatePanelID = updSegmentPanel.UniqueID;
//progress.AssociatedUpdatePanelID = updSegmentPanel.ID;
}
}
}
}

void lnkToggleSementPanel_Click(object sender, EventArgs e)
{
LinkButton lnkToggleSementPanel = senderas LinkButton;
if (lnkToggleSementPanel !=null)
{
Control parentControl =
lnkToggleSementPanel.Parent;
UpdatePanel updSegmentPanel = parentControl.FindControl("updSegmentPanel")as UpdatePanel;

if (updSegmentPanel !=null)
{
Repeater rptSegments = updSegmentPanel.FindControl("rptSegments")as Repeater;
if( rptSegments !=null )
{
List<int> items =new List<int>();
for (int i = 0; i <= Convert.ToInt32(lnkToggleSementPanel.CommandArgument); i++)
items.Add(i);

rptSegments.DataSource = items;
rptSegments.DataBind();
updSegmentPanel.Update();

// Delay added for debugging
System.Threading.Thread.Sleep(1000);
}
}
}


}
}

Another thing that I've found strange is that if I move the assigning of the AssociatedUpdatePanelID property FROM ItemDataBound TO ItemCreated it all stops working and if you check the generated control ID's they've not been given proper IDs, i.e the NamingContainer stops working

No takers on this one? It appears Im just missing one piece of the puzzle but I can't figure out which oneSad


Hi,

Here is a working sample:

<%@. Page Language="C#" %><%@. Import Namespace="System.Collections.Generic" %><!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) { if (!Page.IsPostBack) { List<int> items = new List<int>(); for (int i = 0; i < 5; i++) items.Add(i); this.rptAlternatives.DataSource = items; this.rptAlternatives.DataBind(); } } protected void rptAlternatives_ItemCreated(object sender, RepeaterItemEventArgs e) { //if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item) //{ // LinkButton lnkToggleSementPanel = e.Item.FindControl("lnkToggleSementPanel") as LinkButton; // if (lnkToggleSementPanel != null) // { // lnkToggleSementPanel.Click += new EventHandler(lnkToggleSementPanel_Click); // lnkToggleSementPanel.CommandArgument = e.Item.ItemIndex.ToString(); // this.ScriptManager1.RegisterAsyncPostBackControl(lnkToggleSementPanel); // } //} } protected void rptAlternatives_ItemDataBound(object sender, RepeaterItemEventArgs e) { if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item) { UpdatePanel updSegmentPanel = e.Item.FindControl("updSegmentPanel") as UpdatePanel; if (updSegmentPanel != null) { UpdateProgress progress = e.Item.FindControl("progress") as UpdateProgress; if (progress != null) { progress.DisplayAfter = 0; } } } } protected void rptAlternatives_ItemCommand(object source, RepeaterCommandEventArgs e) { LinkButton lnkToggleSementPanel = e.Item.FindControl("lnkToggleSementPanel") as LinkButton; if (lnkToggleSementPanel != null) { Control parentControl = lnkToggleSementPanel.Parent; UpdatePanel updSegmentPanel = parentControl.FindControl("updSegmentPanel") as UpdatePanel; if (updSegmentPanel != null) { Repeater rptSegments = updSegmentPanel.FindControl("rptSegments") as Repeater; if (rptSegments != null) { List<int> items = new List<int>(); for (int i = 0; i <= e.Item.ItemIndex; i++) items.Add(i); rptSegments.DataSource = items; rptSegments.DataBind(); updSegmentPanel.Update(); // Delay added for debugging System.Threading.Thread.Sleep(2000); } } } }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:repeater id="rptAlternatives" runat="server" onitemcreated="rptAlternatives_ItemCreated" onitemdatabound="rptAlternatives_ItemDataBound" OnItemCommand="rptAlternatives_ItemCommand"> <itemtemplate> <div style="border: 1px solid #000; width: 300px; height: 100px; margin: 10px 0 10px 0;"> <asp:updatepanel id="updSegmentPanel" runat="server" UpdateMode="Conditional" ChildrenAsTriggers="true"> <contenttemplate> <asp:linkbutton id="lnkToggleSementPanel" runat="server" text="Toggle segments"></asp:linkbutton> <asp:repeater id="rptSegments" runat="server"> <headertemplate> <div style="background-color: red; width: 100%;"> </headertemplate> <itemtemplate><%# Container.DataItem%> </itemtemplate> <footertemplate> </div> </footertemplate> </asp:repeater> </contenttemplate> <Triggers> </Triggers> </asp:updatepanel> <asp:updateprogress id="progress" runat="server" AssociatedUpdatePanelID="updSegmentPanel"> <ProgressTemplate> Loading... </ProgressTemplate> </asp:updateprogress> </div> </itemtemplate> </asp:repeater> </div> </form></body></html>

Please try it and compare with your own code.

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

dynamic addhandler not working in update panel

hi all,

i have designed a page, with a place holder in it, the placeholder is inside a updatepanel, the placeholder gets filled with images at load, and when i click the viewcart button it get filled with the image information with few dynamic buttons, i have added addhandler for those buttons, but they are not firring up. i am pasting my code here if some one can help me plz.

Dim

updateorderlnkbtn AsNew button ' this is done at the genearal section of the page to make it globalAddHandler updateorderlnkbtn.click,AddressOf cancelBtn_click ' at page init

please help me

hi all

i have done some other changes to the code but still the same problem, if any one of you can give me some idea that would be highly appreciated

thanks


hi all

I have done some thing here that my 5 static buttons that are created at runtime are working fine now but the problem is with the dynamic table, i am placing a delete button in the dynamic table now the dynamic table is created at runtime and i want the delete button to remove the row.

the other buttons (5 buttons) code is something like this , i have wrote the code behing the load, the problem is that i can't wrote the dynamic table code behind the load, the dynammic table is created when i click a viewcart button

please help

Dyanmically created linkbuttons, within UpdatePanel, is not working

Hello Folks,

I am updating a placeholder, to create some form controls, from my code behind.

I am successful. Now, I want to create a linkbutton, next to each form control i create, that when clicked on, go to the same generic event and read the control's ID (passed by the linkbutton somehow) and then I will do the logic to remove the control from the placeholder. Right now it creates the linkbuttons, but to ensure i don't have duplicate ID's, I add a unique int.tostring on the end of the ID of the linkbuttons. And I added the handler that should send all clicks, from all the linkbuttons to the same event. But I put a breakpoint in that event and when I click any of the linkbuttons, it just refreshes and no change to the page and the breakpoint in the event is never reached. Please let me know if you have any ideas, questions.. a portion of my code, with notes, below...

I am able to create all form elements except buttons, link buttons, etc.

I think the link button creation should be as simple as:

victorylinkBTN.ID ="victorylinkBTN" & VictoryReplicantCount.ToString

AddHandler victorylinkBTN.Click,AddressOf victorylinkBTN_Click

DCP.Controls.Add(victorylinkBTN)

victorylinkBTN.Text ="Del"

Dim vicEventAsNew System.EventArgs()

Is that right? It does create the linkbuttons, but the click fails. It submits, but nothing happens, it just refreshes with nothing changed, and doesn't land on my breakpoint, in the sub below.

Sub victorylinkBTN_Click(ByVal senderAsObject,ByVal eAs System.EventArgs)

Dim linkbutAs LinkButton =CType(sender, LinkButton)

Dim linkbutIDAsString = linkbut.ID.ToString

'do more work……

EndSub

If you have any idea what I am doing wrong, please let me know.

Also, if you have experience with update panels, if I make the update panel conditional, then how would I set each of these linkbuttons to have trigger rights to the related update panel?

Again, thanks for any help ...

Folks,

I have found a cheesy way to do this, by adding javascript on each linkButton created that inserts the linkButton ID into a hidden field's value on the page and then on that linkButton submit, in pageLoad, I read the value of the hidden field to decide to perform the action.

This works, and would take some serious time to explain. Please feel free to email me via the forum contact ability, if you want details.

I am leaving this open, hoping someone in the asp.net team will have a better solution.


Since you dynamically add thelink buttons, you should add it to the PlaceHolder in the Page_Load event every time instead of adding it just the page first load. Because when you only add it the first time the page load, after post back, thelink buttonswill disappear. And itdoesn't land on your breakpoint invictorylinkBTN_Click,There is non victorylinkBTN when your postback.

Try this:

publicpartialclassDefault2 : System.Web.UI.Page

{

protectedvoid Page_Load(object sender,EventArgs e)

{

AddControl(PlaceHolder_ContentRight,"~/WebUserControl.ascx",true);

}

privatevoid AddControl(PlaceHolder PlaceHolder,string ControlPath,bool Clear)

{

Control Control_ToAdd;

Control_ToAdd = LoadControl(ControlPath);

if (Clear)

{

PlaceHolder.Controls.Clear();

}

PlaceHolder.Controls.Add(Control_ToAdd);

}

}

If this help you,don't forget mark it as a answer.Thanks!

Best Regards

Jin-Yu Yin

Duplicate Items in dropdownlist inside an Updatepanel

Hi,

I have been working with Atlas for the past couple of weeks and I have a very simple page with a dropdownlist box inside a updatepanel. I have a button that inserts a value in the back-end database and refresh the dropdownlist. This button is also a trigger for the updatepanel. This dropdownlist is bounded to an ObjectDataSource.

The problem is that on the first click, the values in the dropdownlist are duplicated with the original list and plus the new value. So I have the original list show up twice and the new value at the end. However, on the second click, the dropdownlist is updated correctly with only the new value being appended at the end. Doesn't anyone have the same problem?

ThanksSmile

<atlas:UpdatePanelID="UpdatePanelReason"runat="server"Mode="Conditional">

<ContentTemplate>

<asp:DropDownListID="drpReason"runat="server"AppendDataBoundItems="True"DataSourceID="ObjectDataSource1"DataTextField="ITEM_SUB_TYPE_NAME"DataValueField="PK_ITEM_SUB_TYPE_ID">

<asp:ListItemValue="0">Select Reason</asp:ListItem>

</asp:DropDownList>

</ContentTemplate>

<Triggers>

<atlas:ControlEventTriggerControlID="btnAddReason"EventName="Click"/>

</Triggers>

</atlas:UpdatePanel>

My post-back method to insert a new value in the dropdownlist.

ProtectedSub btnAddReason_Click(ByVal senderAs System.Object,ByVal eAs System.EventArgs)Handles btnAddReason.Click

IfMe.txtNewReason.Text <>String.EmptyThen

Dim lookupMgrAsNew LookupManager

lookupMgr.insertItemSubType(Me.txtNewReason.Text, Session("ItemType"))

Me.drpReason.DataBind()

EndIf

EndSub

Problem solved!! All I have to do is clear all the items in the dropdownlist before calling databinding.

:)

Dummie question about UpdatePanel

I have a problem which can be sumarized in the following:

- UpdatePanel with a button

- Text box outside update panel

- Want button "click" method to update the text in the textbox.

How is this possible? I have read some suggestions (Luis Abreu suggests a "dummie button" with _DoPostBack. The problem is I am very new to asp so have no idea about where and how to place the code and have no idea about how javascript works in the page, so I did not underestand that solution nor how to implement it...

Any help is appreciated!

I've say you should put the things that you want updated inside the UpdatePanel, with a Trigger on the button click event. The button does not have to reside inside the UpdatePanel. So, your example should be reversed, with the UpdatePanel with a textbox and a button outside the UpdatePanel.
Hi,

quick example that illustrates what senyl said above:

<%@. 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 btnUpdate_Click(object sender, EventArgs e) { txtDate.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"> <atlas:ScriptManager ID="scriptManager" runat="server" EnablePartialRendering="true"></atlas:ScriptManager> <atlas:UpdatePanel ID="UpdatePanel1" runat="server"> <Triggers> <atlas:ControlEventTrigger ControlID="btnUpdate" EventName="Click" /> </Triggers> <ContentTemplate> <asp:TextBox ID="txtDate" runat="server"></asp:TextBox> </ContentTemplate> </atlas:UpdatePanel> <asp:Button ID="btnUpdate" runat="server" Text="Update" OnClick="btnUpdate_Click" /> </form></body></html>

senyl:

I've say you should put the things that you want updated inside the UpdatePanel, with a Trigger on the button click event.  The button does not have to reside inside the UpdatePanel.  So, your example should be reversed, with the UpdatePanel with a textbox and a button outside the UpdatePanel.

The problem is that my real scenario is slightly more complicated:

One of the UpdatePanels is a GridView with a column which is a button for "add new row". As it is embedded in the gridview, I can't take it out.

The other updatePanel is a FormView that becomes visible when the former button is clicked. It then shows insert boxes and it has a "insert" button that also needs to be in the formview...to insert the record.

Well, my best advice is to watch that video by Scott Gutherie on the Atlas homepage, where he uses a gridview and a formview with atlas. You could also make the updatepanels render always, and code the triggers properly.

Hope this helps (it probably won't, but it is my best guess)

DropshadowExtender disappear on gridview selected index changes

Hello,

I have a gridview inside a panel wich is inside an updatepanel. My problem is when I click on my gridview and I select a row the shado and the rounded corners of the panel around the gridview disappear.

I can see the dropshadowextender, only on the first page load, after it disappears. I can't find any solution to keep the rounded corner and the shadow

Please try your scenario with the recently available61121 release of the Toolkit (and ASP.NET AJAX Beta 2). If the problem persists, then please reply with acomplete, self-contained sample page that demonstrates the problem so that we can investigate the specific behavior you're seeing. Thank you!

DropShadowExtender

Hi,

I am working on an web-solution, where I have a menubar, that consists of an updatePanel, a WebPartZone and some Panels, that represents different menus. It goes something like this:

UPDATEPANEL

WebParZone

Panel 1 = Shop (example)

Panel 2 = Statistics

Panel X = Something

/WebPartZone

/UPDATEPANEL

How can I use a DropShadowExtender on each Panel?

I believe your DropShadowExtender's target control ID should be that of the UpdatePanel...I am not sure if the DropShadowExtender would work with UpdatePanel, i have never tried it.

But, if it does not work, wrap your updatepanel with another asp:panel control and make your dropshadowextender's targetcontrol id to this this dummy wrapper panel..i am sure this would work..

more on DropShadowExtender herehttp://ajax.asp.net/ajaxtoolkit/DropShadow/DropShadow.aspx

Saturday, March 24, 2012

Dropdowns inside updatepanel flash on postback.

I have 2 dropdown controls inside an updatepanel. One is disabled or enabled dependent on the selection of the other dropdown. The disabled one has its autopostback property set to false. The other one has autopostback=true. When I make selection in dropdown 1, both dropdowns flash. Is there a way to prevent the redrawing of the controls and just have the data in them update?

Thanks,

John

Put the both the DropDownlist control in to its own UpdatePanel.And make the second updatepanel Updatemode ="Conditional" and when you want to second DDL to be enable do it in the code and call the update() method in the UpdatePanel two ..

refer the following link for more information

http://asp.net/ajax/documentation/live/overview/UpdatePanelOverview.aspx

DropDownList, UpdatePanel, ControlEventTrigger and TimerControl affecting other UpdatePane

I've run across a problem so I've created some sample code below that replicates what I'm seeing.

I've got an UpdatePanel(up_Test) that has a control in it. I've got a TimerControl that fires every 2 seconds and my UpdatePanel has a Trigger to refresh on my TimerControl's Tick event.

I've got a DropDownList on the page(ddl_Test), with an AutoPostBack="true", I've got another UpdatePanel on the page that has a Trigger to refresh on my DropDownList's SelectedIndexChanged event. In this UpdatePanel I've got another DropDownList that gets its SelectedIndex set to the SelectedIndex of the first DropDownList.

Everything works as expected, except when I test it with IE6, when the TimerControl fires, the DropDownList in the second UpdatePanel gets refreshed. It doesn't seem to happen(or at least isn't noticable) with IE7(which is on the machine I'd been writing this on).

Basically, I wrote this big page that has a ton of different updatepanel's on it each with triggers to specific controls and that whole section worked great, but then on my masterpage, when I put a gridview with a timercontrol, suddenly, the page practically became unusable as all of the updatepanels suddenly trigger when the TimerControl fires. Is there some work-around I can do, or do I just need to drop the TimerControl and scrap the whole layout?

<

atlas:TimerControlID="tc_Test"runat="server"Interval="2000"Enabled="true"OnTick="tc_Test_Tick"/><atlas:UpdatePanelID="up_Test"runat="server"><ContentTemplate><asp:DropDownListID="ddl_Test"runat="server"></asp:DropDownList></ContentTemplate><Triggers><atlas:ControlEventTriggerControlID="tc_Test"EventName="Tick"/></Triggers></atlas:UpdatePanel><asp:DropDownListID="ddl_Test1"runat="server"AutoPostBack="true"OnSelectedIndexChanged="ddl_Test1_SelectedIndexChanged"/><atlas:UpdatePanelID="up_Test2"runat="server"><ContentTemplate><asp:DropDownListID="ddl_Test2"runat="server"></asp:DropDownList></ContentTemplate><Triggers><atlas:ControlEventTriggerControlID="ddl_Test1"EventName="SelectedIndexChanged"/></Triggers></atlas:UpdatePanel>

protected

void Page_Load(object sender,EventArgs e)

{

if (!Page.IsPostBack)

{

for (int i = 0; i < 10; i++)

{

string itemtext ="This is a long string to make it noticable " + i.ToString();

ddl_Test.Items.Add(itemtext);

ddl_Test1.Items.Add(itemtext);

ddl_Test2.Items.Add(itemtext);

}

}

}

protectedvoid ddl_Test1_SelectedIndexChanged(object sender,EventArgs e)

{

ddl_Test2.SelectedIndex = ddl_Test1.SelectedIndex;

}

protectedvoid tc_Test_Tick(object sender,EventArgs e)

{

Random r=newRandom();

ddl_Test.SelectedIndex = r.Next(9);

}

Mode="Conditional" on the update panels fixes the problem. I guess I just assumed putting in the <trigger> lines caused it to use the triggers but you have to change the updatepanel's mode too.

DropDownList with many entries is slow when EnablePartialRendering = true, but it is fast

Hello together,

I have a big performance problem when I use a DropDownList in an UpdatePanel. This is my code:

ASPX-Page:

<asp:ScriptManager ID="smMain" runat="server" EnablePartialRendering="true">
</asp:ScriptManager>
<asp:UpdatePanel ID="upPartial" runat="server">
<ContentTemplate>
<asp:DropDownList ID="ddlList" runat="server" />
<asp:Button ID="btnPostBack" runat="server" Text="PostBack" />
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdateProgress ID="progress" runat="server" DisplayAfter="0">
<ProgressTemplate>
Wait Please...
</ProgressTemplate>
</asp:UpdateProgress>

CodeBehind:

protected void Page_Load(object sender, EventArgs e)
{
for (int i = 0; i < 10000; i++)
{
((DropDownList)this.upPartial.FindControl("ddlList")).Items.Add(new ListItem("Value " + i.ToString(), i.ToString()));
}
}

When I click the button on this page it takes about 1 minute to complete the partial postback. But it is a simple postback with no other code to execute. When I set EnablePartialRendering = false in the ScriptManager the same postback executes in about 1 second.

Can somebody tell me what is the problem with the partial postpack?

Thanks and best regards

Gunther

Hi Gunther,

Well this is an issue that i have seen before on this forum. As far as i know you can't fix this when you take a look at the Ajax framwork. I think that a dropdownlist with 10000 rows isn't a very user friendly dropdownlist. Why are you putting so much items in 1 dropdownlist? Isn't possible to filter some of the items by the selection that a user can make in multiple dropdownlist. For example. If you have a dropdownlist with 10000 projectteams it could be possible to add a few selections before you select the project team like:

Select a Company

Select a Department

Select a Projectteam

This will filter the project team dropdownlist because you first selected a specific company and department so there are less projectteams left. I hope this helps

Regards,


Gunther,

Its not only the problem with the dropdown list, but also with gridview when i has more nubmer of rows.

when i removed the ajax controls, it worked fine.

sansav_p


Thank you for your answers.

The problem is that we are in a production environment, where I can't seperate the filter into several filters and I really need all the entries in the dropdownlist at the moment.

The thing I can't understand is why the page is fast without partial rendering and very very slow with partial rendering. I think I do nothing special and a solution for this should exist. Perhaps it can be solved with a dropdownlist from another vendor.

I will be happy with every solution or help I can get.

DropdownList Update

Hi,

I have modified the sample program for Data Demo. I've used ASP.NET AJAX....I have a dropdownlist and a gridview inside an updatepanel. Also, im connected thru a objectdatasource. the dropdownlist gets value from objectdatasource1. The value comes from a distinct state from the author table while the gridview is connected to objectdatasource2. The value for objectdatasource2 comes from auther table where state = to the dropdownlist selected value.

Now what i want to achieve is that if i edit the state in the gridview my dropdownlist will be automacatically refresh. I tried adding <asp:AsyncPostBackTriggerControlID="GridView1"EventName="SelectedIndexChanged"/> to the updatepanel. I was able to save the changes but the dropdownlist doesnt.

Thanks

2lits

When both the controls that cause a refresh to the updatepanel are inside it, you can use the ChildrenAsTriggers property of the UpdatePanel. Set it to True, and your Dropdownlist should be re-binding.

Thanks


The ChildrenAsTriggers was already set to true but still my dropdownlist is not re-binding...any other thoughts? thanks!


Is your updateMode on conditional basis?

Thanks


it was set to always.

Thanks


I'd say step one is to remove the UpdatePanel and see if this is working in regular postback mode. If it is, then we need to figure out what's going wrong with your UpdatePanels.

I'd want to see some code at that point... is there just one UpdatePanel on the page? Is the GridView inside it? Is the DropDownList?


Yes There is only one Update Panel. The Gridview , dropdownlist, and the sources are inside it.

here's my code :

<formid="form1"runat="server"><asp:ScriptManagerID="ScriptManager1"runat="server"/> <divtitle="My First AJAX-Enabled Data Driven Page"><asp:UpdatePanelID="UpdatePanel1"runat="server"UpdateMode="Conditional"><ContentTemplate> <asp:DropDownListID="DropDownList1"runat="server"DataSourceID="ObjectDataSource1"DataTextField="State"DataValueField="State"AutoPostBack=True></asp:DropDownList><asp:GridViewID="GridView1"runat="server"AllowPaging="True"AutoGenerateColumns="False"DataSourceID="ObjectDataSource2"AllowSorting="True"DataKeyNames="AuthorID"><Columns><asp:CommandFieldShowEditButton="True"ShowSelectButton="True"/><asp:BoundFieldDataField="AuthorID"HeaderText="AuthorID"InsertVisible="False"ReadOnly="True"SortExpression="AuthorID"/><asp:BoundFieldDataField="FirstName"HeaderText="FirstName"SortExpression="FirstName"/><asp:BoundFieldDataField="LastName"HeaderText="LastName"SortExpression="LastName"/><asp:BoundFieldDataField="City"HeaderText="City"SortExpression="City"/><asp:BoundFieldDataField="State"HeaderText="State"SortExpression="State"/><asp:BoundFieldDataField="Zip"HeaderText="Zip"SortExpression="Zip"/><asp:BoundFieldDataField="Phone"HeaderText="Phone"SortExpression="Phone"/></Columns></asp:GridView><br/> <asp:ObjectDataSourceID="ObjectDataSource2"runat="server"OldValuesParameterFormatString="{0}"SelectMethod="GetData"TypeName="DataSet2TableAdapters.SelectAuthorsTableAdapter"UpdateMethod="Update"><SelectParameters><asp:ControlParameterControlID="DropDownList1"Name="State"PropertyName="SelectedValue"Type="String"/></SelectParameters><UpdateParameters><asp:ParameterName="AuthorID"Type="Int32"/><asp:ParameterName="FirstName"Type="String"/><asp:ParameterName="LastName"Type="String"/><asp:ParameterName="City"Type="String"/><asp:ParameterName="State"Type="String"/><asp:ParameterName="Zip"Type="String"/><asp:ParameterName="Phone"Type="String"/></UpdateParameters></asp:ObjectDataSource><asp:ObjectDataSourceID="ObjectDataSource1"runat="server"OldValuesParameterFormatString="original_{0}"SelectMethod="GetDataState"TypeName="DataSet2TableAdapters.StateListTableAdapter"></asp:ObjectDataSource><br/></ContentTemplate><Triggers><asp:AsyncPostBackTriggerControlID="DropDownList1"EventName="SelectedIndexChanged"/><asp:AsyncPostBackTriggerControlID="GridView1"EventName="RowUpdated"/></Triggers></asp:UpdatePanel> </div></form>
The updatemode is set to always. I just test it to conditional.

The updatemode is set to always. I just test it to conditional.

Thanks


And what's supposed to happen to the DropDownList when you edit the GridView?

Did you try removing the UpdatePanel? I have a feeling this isn't working with regular postbacks either and doesn't really have to do with AJAX, since your UpdatePanel code looks correct.


I should be able to see the updates in the state. example if I change the state from MI to NW upon save i should be able to see NW added in the dropdownlist. It is working on the regular postback...

Steve Marx:

I have a feeling this isn't working with regular postbacks either and doesn't really have to do with AJAX, since your UpdatePanel code looks correct.

This is to do with AJAX. When the DropDownList is binded declaratively, the list wont get refreshed on the triggers of the updatepanel. You need to explicitly bind the dropdownlist in the events specified on the updatepanel. But if have you had used the same ObjectSource for both the GridView and DropDownList, then sure the list gets updated.

Since the OP is working on the same database table, one ObjectDataSource is enough and when the GridView UpdateCommand is called, the data for the DropDownList is pulled again.

Thanks


e_screw, I don't quite understand... the databinding should work exactly the same way in a regular postback and an async postback. I'm still having trouble figuring out how this can work without the UpdatePanel but fail with it.

Certainly the DropDownList has to be bound again in the event handler, but what does that have to do with AJAX?


yes..thats also my understanding. How does the updatepanel rebind the data?

Thanks so much!


Steve Marx:

... the databinding should work exactly the same way in a regular postback and an async postback. I'm still having trouble figuring out how this can work without the UpdatePanel but fail with it. Certainly the DropDownList has to be bound again in the event handler, but what does that have to do with AJAX?

I am not sure though (still learning AJAX), the DataBinding of the controls (set declaratively using DataSourceID) will be started before the PreRender event of the page and not sure if the necessary client-scripts for that will be injected into the page by AJAX. I have checked with a different ObjectDataSource (each for Dropdownlist and GridView), and there was no client-script generated for the DropDownList unless there was explicit binding. When you are using the same ObjectDataSource for both the controls, there was client-script inject for both even if there was no explicit binding.

Thanks

Dropdownlist not working within an UpdatePanel

I have a MasterPage with a ScriptManager EnablePartialRendering set to true.

On my AddDeceseadInfo.aspx page I have multipe textboxes and a dropdownlist all wrapped in a UpdatePanel. Also on the AddDeceasedInfo.aspx page (content) I have a ProxyScriptManager.

When I pick a value from the Dropdownlist the value is always "".

When I set AutoPostBack to true my ValidationControl fires and tells me the dropdownlist can not be empty which at that point it is.

When I set the AutoPostBack to false once a pick a value from the dropdownlist all the data in the dropdownlist disappears.

Can somebody help out a AJAX newbie............Cheers!

protectedvoid Page_Load(object sender,EventArgs e)

{

TextBoxFirstName.Focus();

if (!IsPostBack)

{

//Gets the languageID for the current user.

int languageID =LanguageUtility.GetLanguageIDByTwoLetterISOLanguageName();

DropDownListCauseOfDeath.DataSource = BLL.CauseOfDeath.GetCausesOfDeathByLanguageID(languageID);

//The field in the data source which provides the item text.

DropDownListCauseOfDeath.DataTextField ="CauseOfDeath";DropDownListCauseOfDeath.DataValueField ="CauseOfDeathID";

DropDownListCauseOfDeath.DataBind();

}

}

protectedvoid ButtonReset_Click(object sender,EventArgs e)

{

Utility.WebUtility.ClearAllTextBoxes(this);

}

protectedvoid ButtonSubmit_Click(object sender,EventArgs e)

{

if (Page.IsValid)

{

string firstName =HttpUtility.HtmlEncode(TextBoxFirstName.Text).Trim();

string middleName =HttpUtility.HtmlEncode(TextBoxMiddleName.Text).Trim();

string lastName =HttpUtility.HtmlEncode(TextBoxLastName.Text).Trim();

string nickName =HttpUtility.HtmlEncode(TextBoxNickName.Text).Trim();

DateTime dateOfBirth =Convert.ToDateTime(HttpUtility.HtmlEncode(TextBoxDateOfBirth.Text).Trim());

DateTime dateOfDeath =Convert.ToDateTime(HttpUtility.HtmlEncode(TextBoxDateOfDeath.Text).Trim());

int causeOfDeathID =Convert.ToInt32(DropDownListCauseOfDeath.SelectedValue);string birthPlace =HttpUtility.HtmlEncode(TextBoxBirthPlace.Text).Trim();

}

else

{

}

}

}

Set AutoPostBack to true and also set CauseValidation property to false


Set the EnableClientScript property to false on your validation control. Validators aren't supported in an UpdatePanel, this may be causing you issues,see Item #4 for more information

-Damien


I guess my post was not clear but the answers posted did not really help. My DropDownList is inside an UpdatePanel.

The ScriptManager is set to enable patial rendering.

AutoPostBack is set to true.

My UpdatePanel has UpdateMode set to Conditional

I populate the DropDownList with values from my database. When the page loads the values are there in the DropDownList. When I go and pick a value the data from the DropDownList disappears. Basically I end up with a empty DropDownList. Values gone................

When I set the AutoPostBack property to false the data stays in the DropDownList after I pick a value but when I hit the submit button the Validation control fires because the DropDownList is all of a sudden empty again.

I am running the latest Versions of ASP.Net Ajax and was under the impress the validator problems have been solved in the latest version. It seems to work on all my other froms that I use the UpdatePanel. The Validator controls and UpdatePanel work nicely together.

There seem to be no examples on the web where somebody has on DropDownList in an UpdatePanel and simple wants to get the value from that DropDownList and the additional TextBoxes once the Submit button is clicked.

I watched some of the ASP.Net videos and there are some Extenders that might be useful but it is too much work. Isn't there a why of making a simple DropDownList work within a UpdatePanel. So I can get the value from it.


How are you binding the list; are you possibly clearing it on the postback? Do you have ViewState enabled for the DropDownList?

Also, I'm using a DropDownList in an UpdatePanel successfully so it does work.

-Damien


Thanks for your reply, here is my Page_Load

protectedvoid Page_Load(object sender,EventArgs e)

{

TextBoxFirstName.Focus();

if (!IsPostBack)

{

//Gets the languageID for the current user.

int languageID =LanguageUtility.GetLanguageIDByTwoLetterISOLanguageName();

DropDownListCauseOfDeath.DataSource = BLL.CauseOfDeath.GetCausesOfDeathByLanguageID(languageID);

//The field in the data source which provides the item text.

DropDownListCauseOfDeath.DataTextField ="CauseOfDeath";DropDownListCauseOfDeath.DataValueField ="CauseOfDeathID";

DropDownListCauseOfDeath.DataBind();

}

}


If I comment if(!Ispostback) out then the form works as it should the only problem is the that the DropDownList gets bound again after I hit the submit button and therefore the the ID returned by the DropDownList is always 1. Somebody it sitting on my brain and I can't figure this out. Any ideas? Thanks, Newbie

protectedvoid Page_Load(object sender,EventArgs e)

{

TextBoxFirstName.Focus();

//if (!IsPostBack)

//{

//Gets the languageID for the current user.

int languageID =LanguageUtility.GetLanguageIDByTwoLetterISOLanguageName();

DropDownListCauseOfDeath.DataSource = BLL.CauseOfDeath.GetCausesOfDeathByLanguageID(languageID);

//The field in the data source which provides the item text.

DropDownListCauseOfDeath.DataTextField ="CauseOfDeath";DropDownListCauseOfDeath.DataValueField ="CauseOfDeathID";

DropDownListCauseOfDeath.DataBind();

//}

}


Just fixed the problem. I overrode the OnInit event like this

protectedoverridevoid OnInit(EventArgs e)

{

base.OnInit(e);

PopulateDropDownList();

}

and added a PopulateDropDownList() method

privatevoid PopulateDropDownList()

{

//Gets the languageID for the current user.

int languageID =LanguageUtility.GetLanguageIDByTwoLetterISOLanguageName();

DropDownListCauseOfDeath.DataSource = BLL.CauseOfDeath.GetCausesOfDeathByLanguageID(languageID);

//The field in the data source which provides the item text.

DropDownListCauseOfDeath.DataTextField ="CauseOfDeath";DropDownListCauseOfDeath.DataValueField ="CauseOfDeathID";

DropDownListCauseOfDeath.DataBind();

}

Set the AutoPostBack to false

EnableViewState to true

UpdatePanel to Conditional

ScriptManager EnablePartialRendering to true

And it is all working now like a charm. DropDownList works in UpdatePanel and so do the validation controls. Thanks Microsoft.....................


Thank you for posting the solution. You just made my day!

DropDownList inside UpdatePanel Performance Issue (IE7 vs. FireFox)

hey,

I have a weird performance issue that i just don't know how to explain:

I built a simple page that has a dropdownlist and a button controls, both of them are inside an update panel.

When a user clicks on the button for the first time, it loads the dropdownlist with 2000 items (just for testing purposes). On the second click, it clears the dropdownlist and fill it with only 2 items. The code is very simple. All in the code behind

I tried the page on IE7 and FireFox. In IE7: the page pauses on the second load (the clear of the 2000 items and the load of the 2 items), while firefox is so much faster.

I removed the update panel and tried the page again, its fast on both IE7 and FireFox. Also tried to add some javascript code to clear the list on the client side, its also too slow.

Does anyone knows a way how to improve it on IE7 :) beside uninstalling it and use FireFox instead :)


thnx 4 ur time

Honestly, I had a lot of performance issues with IE with several of the AJAX controls. We ended up buying a product that is much better than the free one.


i've never seen a dropdownlist that has 2000 items in it before.

what you might want to do is categorizing the items into group(s) and use 2 or more dropdownlist(s). definitely will increase your performance.


Thanks 4 the reply. But its not just about 2000 items, even if you make them 1000 (unfortunately, this is the business logic, that i have to display all the items). Why does FireFox is so much faster, is there something i can do to optimize it.

Thanks