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

Wednesday, March 28, 2012

link buttons in user control not recognised by updatePanel

Hello...

I have a usercontol that has some linkbuttons.....and an updatePanel...i put the linkbutton ID's in the Trigger section of the updatePanel, but I'm getting an error that the updatePanel does not recognise the button ID's I have passed in...

how do I fix this? thanks

Hi,

Update Panel is not gonna recognize those link buttons because they are inside of usercontrol. You need to create user control event for each link button event. For example,

CustomControl.ascx

<%@. Control Language="C#" AutoEventWireup="true" CodeFile="CustomControl.ascx.cs" Inherits="CustomControl" %>
<asp:LinkButton ID="lnkTest" runat="server" OnClick="lnkTest_Click">Test Button</asp:LinkButton

CustomControl.ascx.cs

public partial class CustomControl : System.Web.UI.UserControl
{
public delegate void TestHandler(object sender, EventArgs e);
public event TestHandler LinkClicked;

protected void Page_Load(object sender, EventArgs e)
{

}
protected void lnkTest_Click(object sender, EventArgs e)
{
if (LinkClicked != null)
LinkClicked(this, new EventArgs());
}
}

test.aspx

<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="CustomControl1" EventName="DoYourBussiness" />
</Triggers>
<ContentTemplate>
<uc1:CustomControl ID="CustomControl1" runat="server" OnLinkClicked="DoYourBussiness" />
</ContentTemplate>
</asp:UpdatePanel


Hi,

thanks for this, how about for normal hyperlinks?... (instead of linkButons)... can something similar be done?

thanks


Hi,

Normal hyperlinks do not have OnClick event. LinkButton looks the same as HyperLink, but has OnClick event.

LinkButton & UpdatePanel

I have dynamically added a linkbutton inside of an updatepanel. For some reason that I don't understand when I click on the linkbutton the entire page refreshes. I can't figure out why. It's in a content page which uses a master page. I've tried using Conditional & Always. I've tried adding anAsyncPostBackTrigger for the linkbutton Click, but no matter what the entire page refreshes. If I use a non-dynamically added linkbutton (see LinkButton1 below) it only updates the updatepanel. Any ideas?

Here are some code snippets:

<asp:UpdatePanel ID="FlyoutUpdate" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Panel ID="pnlSingleCalItem" runat="server" Height="270px" Width="350px">
<asp:Label ID="lblDateHeader" runat="server" Text="test"></asp:Label>
<br /><br />
<table width="100%">
<tr><td align="left" style="background-color:#E6E7E8">
<asp:Label ID="lblCalTitle" Font-Bold="true" Font-Size="13px" Font-Names="Arial" ForeColor="#96B96E" runat="server" Text="Title"></asp:Label>
<br />
<asp:Label ID="lblCalLocation" runat="server" Font-Size="12px" Font-Names="Arial" ForeColor="#BA906C" Text="Location"></asp:Label></td></tr>
<tr><td align="left"><asp:TextBox BorderWidth="0px" BorderStyle="none" Font-Size="11px" Font-Names="Arial" ID="txtCalMessage" runat="server" Width="350px" Height="200px" TextMode="multiLine"></asp:TextBox></td></tr>
</table>
</asp:Panel>
<asp:Panel ID="pnlMultipleCalItems" runat="server" Height="270px" Width="350px">
<asp:Label ID="lblDateHeaderMulti" runat="server" Text="test"></asp:Label>
<br /><br />
<asp:Table ID="tblMultipleCalItems" BorderWidth="0px" BorderStyle="none" runat="server">
</asp:Table>
<br /><br />
<asp:LinkButton ID="LinkButton1" runat="server">LinkButton</asp:LinkButton>
</asp:Panel>

</ContentTemplate>
</asp:UpdatePanel>

Dim hypAs New LinkButtonhyp.Text = varNameAddHandler hyp.Click,New EventHandler(AddressOf hyp_Click)hyp.Visible = varVisibleDim trAs New TableRow()Dim td1As New TableCell()td1.Controls.Add(hyp)Dim tblAs Tabletbl = pnlMultipleCalItems.FindControl("tblMultipleCalItems")tr.Cells.Add(td1)tbl.Rows.Add(tr)

Hi

When you add something to the page dynamically,you should add it everytime the page been posted back.

If you don't add it again when the page been Ayncpostbacked,the contorl is null,and it's click event handler method isn't executed.

Thanks


Hi Jim-Yu,

That is a good idea, but NO... LinkButton as a child control of a custom control causes a PostBack not a Callback. Here's some sample code the shows the bug in LinkButton. Put this custom control on an UpdatePanel and notice the "button" does a nice callback, and the "link" does a postback.

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

namespace testing
{
/// <summary>
/// Summary description for Test
/// </summary>
public class Test : Control, INamingContainer
{
public Test()
{
//
// TODO: Add constructor logic here
//
}

protected override void CreateChildControls()
{
CreateThem();
base.CreateChildControls();
}

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

private void CreateThem()
{
LinkButton lnk = new LinkButton();
lnk.Text = "link";
Button btn = new Button();
btn.Text = "button";

this.Controls.Add(btn);
this.Controls.Add(lnk);
}
}
}


Hincornillon,

Thank you for your feedback,

You can change your code to:

private void CreateThem()
{
LinkButton lnk = new LinkButton();
this.Controls.Add(lnk);
lnk.Text = "link";
ScriptManager.GetCurrent(this.Page).RegisterAsyncPostBackControl(lnk);

Button btn = new Button();
this.Controls.Add(btn);
btn.Text = "button";
// ScriptManager.GetCurrent(this.Page).RegisterAsyncPostBackControl(btn);
}

Best Regards


I'm afraid it's still not working. When I dynamically create the controls I'm putting them in a Session array. Then in page_init I'm re-generating them like this below. When I'm looping through the Request.Form, I never see the link button.

If Session("ServerControls")IsNotNothingThen
aServerControls =TryCast(Session("ServerControls"), ArrayList)
Else
aServerControls =New ArrayList()
EndIf

ForEach strAsStringIn aServerControls
Dim hypAsNew LinkButton
Dim hypNameAsString = str
hypName = Replace(hypName,"/","_")
hyp.Text = hypName
AddHandler hyp.Click,New EventHandler(AddressOf hyp_Click)
pnlMultipleCalItems.Controls.Add(hyp)
ScriptManager.GetCurrent(Me.Page).RegisterAsyncPostBackControl(hyp)
Next

'Detect what caused the postback
Dim obj
ForEach objIn Request.Form

Next


Since there is a limited amount of controls to create, I manually created them and am just setting them either visible or not. It was faster. Thanks for the help!

Linkbutton inside atlas:UpdatePanel

Hi All,

I am having few linkbuttons inside an atlas:UpdatePanel. I have placed these inside UpdatePanel as I have to regularly change the text of this linkbuttons.

When I click on these linkbuttons it is actually supposed to update a DataGrid which is placed outside atlas:updatepanel, but in same page. When I debug and see, the Onclick code for the Linbutton is called and also the code necessary to update the Datagrid is also executed. But for some reason, in display the Datagrid is not changing. Is this got something to do with the positioning of grid in page? it is outside updatepanel.

I will copy the required parts of code here . Please help.

In aspx page :

<atlas:TimerControl ID="tmrUpdate" runat="server" Enabled="true" Interval="300000" OnTick="SetIndicatorCount"></atlas:TimerControl>
<atlas:UpdatePanel ID="pnlUpdate" RenderMode="Inline" runat="server">
<ContentTemplate>
<table style="background-color:whitesmoke;font-size:smaller" cellpadding="2" cellspacing="0">
<tr class="DisplayHeader">
<td class="DisplayHeader" colspan="4" align="left">
<asp:Label ID="Label2" runat="server" Text="Driver Exceptions"></asp:Label>
</td>
</tr>
<tr>
<td style="height: 19px">
<cc1:LinkButton ID="lnkTrainersAvailable" Text = "Trainers Available" runat="server" OnClick="lnkTrainersAvailable_Click" ></cc1:LinkButton>
</td>
<td style="height: 19px">
<cc1:LinkButton ID="lnkServiceExceptions" Text="Service Exceptions" runat="server" OnClick="lnkServiceExceptions_Click"></cc1:LinkButton>

</td>
<td style="height: 19px">
<cc1:LinkButton ID="lnkUnreadMessages" Text = "Unread Messages" runat="server" OnClick="lnkUnreadMessages_Click"></cc1:LinkButton>
</td>
<td style="height: 19px">
<cc1:LinkButton ID="lnkHoursNotIn" Text="Hours Not In" runat="server" OnClick="lnkHoursNotIn_Click" ></cc1:LinkButton>
</td>
</tr>

<tr>
<td>
<cc1:LinkButton ID="lnkDriversAvailable" Text = "Drivers Available" runat="server" OnClick="lnkDriversAvailable_Click"></cc1:LinkButton>
</td>
<td>
<cc1:LinkButton ID="lnkContactDue" Text = "Contacts Due" runat="server" OnClick="lnkContactDue_Click" ></cc1:LinkButton>

</td>
<td>
<cc1:LinkButton ID="lnkMaintenanceDue" Text = "Maintenance Due" runat="server" OnClick="lnkMaintenanceDue_Click" ></cc1:LinkButton>
</td>
<td>
<cc1:LinkButton ID="lnkFreeTimeExpired" Text = "Free Time Expired" runat="server" OnClick="lnkFreeTimeExpired_Click" ></cc1:LinkButton>
</td>
</tr>
<tr>
<td style="height: 19px">
<cc1:LinkButton ID="lnkMissedCalendars" Text = "Calendar Due" runat="server" Enabled="true" OnClick="lnkMissedCalendars_Click"></cc1:LinkButton>
</td>
<td style="height: 19px">
<cc1:LinkButton ID="lnkDriverWorkflowRequired" Text = "Driver Workflow Req." runat="server" Enabled="false"></cc1:LinkButton>
</td>
<td style="height: 19px">
<cc1:LinkButton ID="lnkTrackingEarly" Text = "Tracking Early" runat="server" OnClick="lnkTrackingEarly_Click" ></cc1:LinkButton>
</td>
<td style="height: 19px">
<cc1:LinkButton ID="lnkCurrentDeliveries" Text="Current Deliveries" runat="server" OnClick="lnkCurrentDeliveries_Click" ></cc1:LinkButton>
</td>
</tr>
<tr>

<td>
<cc1:LinkButton ID="lnkDetention" Text = "Detention Pay" runat="server" OnClick="lnkDetention_Click"></cc1:LinkButton>
</td>
<td>
<cc1:LinkButton ID="lnkSafteyFollowUp" Text = "Safety Follow up/Audit" runat="server" Enabled="false"></cc1:LinkButton>

</td>
<td>
<cc1:LinkButton ID="lnkTrackingLate" Text = "Tracking Late" runat="server" OnClick="lnkTrackingLate_Click" ></cc1:LinkButton>
</td>
<td>
<cc1:LinkButton ID="lnkDiaryFollowUp" Text = "Diary Follow Up" runat="server" OnClick="lnkDiaryFollowUp_Click"></cc1:LinkButton>
</td>


</tr>
</table>
</ContentTemplate>
<Triggers>
<atlas:ControlEventTrigger ControlID="tmrUpdate" EventName="Tick" />
</Triggers></atlas:UpdatePanel>
<tr>
<td colspan="2">
<uc1:grdDriverCurrentInformationDisplay ID="_grdDriverCurrentInformationDisplay" runat="server" ></uc1:grdDriverCurrentInformationDisplay>
</td>
</tr>

Actually the grid is inside the User control, grdDriverCurrentInformationDisplay.

In aspx.cs the code for Linkbutton clicks which are inside updatepanel are there :

protectedvoid lnkHoursNotIn_Click(object sender,EventArgs e)

{

try

{

lblDrivers.Text ="Hours Not in Drivers ";this.LoadDriverIndicators(RTI.DataLayerV2.RTIDriver.DMDriverIndicator.MessagingIndicatorTypeEnum.HoursNotIn);

}

catch (RTI.FrameworkV2.BrokenRulesException bex)

{

this.Messages = bex.Messages;

}

}

////One method used to retreive the information for the supervisor codes, where clause and indicator typepublic void LoadDriverIndicators(RTI.DataLayerV2.RTIDriver.DMDriverIndicator.MessagingIndicatorTypeEnum indicatorType) {//retrieves the correct supervisorcodes and the where cluase from the grid where they stored in a hidden text boxstring supervisor =this._grdDriverCurrentInformationDisplay.GetSupervisorCode();string whereClause =this._grdDriverCurrentInformationDisplay.GetWhereClause();if (String.IsNullOrEmpty(supervisor))throw new Exception("Must enter a supervisor code");//If the messages are choosen it loads the drivers with unreadmessages from the communication system //otherwise the indicators are loaded from the driver database //Each time a link button is clicked the information is retrieved nothing is stored in view state RTI.Business.DriverManagement.DriverInfo.DriverIndicator indicator =new RTI.Business.DriverManagement.DriverInfo.DriverIndicator(); List indicatorList =new List();if (indicatorType == RTI.DataLayerV2.RTIDriver.DMDriverIndicator.MessagingIndicatorTypeEnum.UnreadMessages) { indicatorList = FleetManager.FillGrid.GetDriverInformationRows(indicator.LoadDriverInformationForUnreadMessage(supervisor, whereClause, RTI.CommonV2.Constants.CommunicationMessageCodes.FreeForm)); }else if (indicatorType == RTI.DataLayerV2.RTIDriver.DMDriverIndicator.MessagingIndicatorTypeEnum.ServiceExceptions) { indicatorList = FleetManager.FillGrid.GetDriverInformationRows(indicator.LoadDriverInformationForServiceExceptions(supervisor, whereClause)); }else if (indicatorType == RTI.DataLayerV2.RTIDriver.DMDriverIndicator.MessagingIndicatorTypeEnum.DiaryFollowUp) { indicatorList = FleetManager.FillGrid.GetDriverInformationRows(indicator.LoadDriverInformationForDiaryFollowup(supervisor, whereClause)); }else { indicatorList = FleetManager.FillGrid.GetDriverInformationRows(indicator.LoadDriverInformationAndIndicator(supervisor, whereClause, indicatorType));if (indicatorType == RTI.DataLayerV2.RTIDriver.DMDriverIndicator.MessagingIndicatorTypeEnum.TrackingLate) { indicatorList.Sort(delegate(FleetManager.FillGrid.DriverInformation d1, FleetManager.FillGrid.DriverInformation d2) {return d1.LateMinutes.CompareTo(d2.LateMinutes); }); indicatorList.Reverse(); } }this._grdDriverCurrentInformationDisplay.ClearGrid();if (indicatorList.Count > 0) { RTI.Business.DriverManagement.DriverInfo.DriverIndicator indicators =new RTI.Business.DriverManagement.DriverInfo.DriverIndicator(); RTI.DataLayerV2.RTIDriver.DMIndicatorCountDataTable table = indicators.LoadIndicatorCount(supervisor, whereClause);for (int k = 0; k < table.DataTable.Rows.Count; k++) { table.Index = k;if (table.IndicatorType == Convert.ToInt32(RTI.DataLayerV2.RTIDriver.DMDriverIndicator.MessagingIndicatorTypeEnum.HoursNotIn)) {if (indicatorType == RTI.DataLayerV2.RTIDriver.DMDriverIndicator.MessagingIndicatorTypeEnum.HoursNotIn) {int hoursCount = 0;for (int i = 0; i < indicatorList.Count; i++) {if (indicatorList[i].HomeCity.ToString().Trim().Replace(" ",string.Empty).Trim() == indicatorList[i].DestinationLocation.ToString().Trim().Replace(" ",string.Empty).Trim()) { indicatorList.Remove(indicatorList[i]); i--; hoursCount++; } }//RTI.Business.DriverManagement.DriverInfo.DriverIndicator indicators = new RTI.Business.DriverManagement.DriverInfo.DriverIndicator(); //RTI.DataLayerV2.RTIDriver.DMIndicatorCountDataTable table = indicators.LoadIndicatorCount(supervisor, whereClause);int count = Convert.ToInt32(table.Total) - hoursCount; lnkHoursNotIn.Text = String.Format("Hours Not In ({0})", count); } } }this._grdDriverCurrentInformationDisplay.LoadByDriver(indicatorList, indicatorType);this.lblDrivers.Text += indicatorList.Count.ToString(); }else {this.AddFeedbackMessage("There are no Drivers that qualify for the indicator"); } }

Please tell why the grid is not updated.

Regards,

Allen.

It's not getting updated because it's not in an updatepanel, and ithe page is not doing a full postback. Read up on update panels at ajax.asp.net/docs to see how the partial page rendering model works.


Is it that I have to include the user control which is having the DataGrid also inside The atlas:UpdatePanel? As Linkbutton's functionality is entirely different why is it required that grid also be in the Updatepanel. It's not a problem even if the entire page refreshes on click of linkbutton.

Please advise.


No, it doesn't have to be in the same updatepanel, just *an* updatepanel. your other option is to set the linkbutton up as a postback control (which tells the updatepanel to go ahead and post the whole page back even though it's inside the updp).


Enabling Partial-Page Updates

TheUpdatePanel control requires aScriptManager control in the Web page. By default, partial-page updates are enabled because the default value of theEnablePartialRendering property of theScriptManager control istrue.

The following example shows markup that defines aScriptManager control and anUpdatePanel control on a page. TheUpdatePanel control contains aButton control that refreshes the content inside the panel when you click it. By default, theChildrenAsTriggers property istrue. Therefore, theButton control acts as an asynchronous postback control.

You have to set LinkButtons PostBack property, so it postbac the page.

http://ajax.asp.net/docs/overview/UpdatePanelOverview.aspx

Linkbutton not working, Imagebutton OK

I placed a usercontrol inside an updatepanel.

The usercontrol has a placeholder, and to that placeholder I add imagebuttons and linkbuttons.

When the imagebuttons are clicked, a partial update of the page is done = GOODSmile

When an linkbutton is clicked, a full update of the page is done = BADAngry (No javascript errors whatsoever).

Does asp.net ajax treat this two types of controls differently? Did I forget to do extra steps?

Regards,

Fizgig



Does anyone have a solution for this? I'm getting the same results with a <asp:LinkButton>. When I try with <asp:Button>, it works perfectly.

This works for me.

<formid="form1"runat="server"><asp:ScriptManagerID="ScriptManager1"runat="server"/><asp:UpdatePanelID="UpdatePanel1"runat="server"UpdateMode="Conditional"><ContentTemplate><asp:PlaceHolderID="PlaceHolder1"runat="server"><asp:ImageButtonID="ImageButton1"ImageUrl="Untitled-1.gif"runat="server"/><br/><br/><asp:LinkButtonID="LinkButton1"runat="server">LinkButton</asp:LinkButton><br/><br/></asp:PlaceHolder><asp:LabelID="lblTest"runat="server"Text="Label"></asp:Label></ContentTemplate></asp:UpdatePanel><div><asp:LabelID="lblTest2"runat="server"Text="Label"></asp:Label></div></form>

Hi Fizgig,

I tried dynamic imageButton, it works fine.

See this:

using System;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 Ajax_Default2 : System.Web.UI.Page{protected void Page_Load(object sender, EventArgs e) { LinkButton lb =new LinkButton();this.PlaceHolder1.Controls.Add(lb); lb.Text ="Linkbutton"; lb.ID ="lb1"; lb.Click +=new EventHandler(lb_Click); ImageButton ib =new ImageButton();this.PlaceHolder1.Controls.Add(ib); ib.ID ="ib1"; ib.ImageUrl ="~/images/add.gif"; ib.Click +=new ImageClickEventHandler(ib_Click); Label2.Text = DateTime.Now.ToString(); }void ib_Click(object sender, ImageClickEventArgs e) { Label1.Text ="ib1 clicked on " + DateTime.Now.ToString(); }void lb_Click(object sender, EventArgs e) { Label1.Text ="lb1 clicked on " + DateTime.Now.ToString(); }}

<asp:UpdatePanel ID="UpdatePanel1" runat="server"> <ContentTemplate> <asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder> <br /> <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label> </ContentTemplate> </asp:UpdatePanel> <asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>

Maybe it's fixed in the current Ajax version. Thanx.

I am receiving the same error that was reported in the original post. In my case I have a link button and an image button and so I'm able to hack this together by setting the OnClientClick property of the LinkButton to <%# "document.getElementById('" + Thumbnail.ClientID + "').click();return false;" %> - which is not very elegant, but works fine. Hopefully later I'll have a chance to better isolate this issue - I've run into it a couple times, but am not sure what the variable is yet.


I found that you have to add a trigger for the link button, so here's what you have to add, where lb is my linkbutton, and upPanel is the update panel that contains the link button...

AsyncPostBackTrigger asbt = new AsyncPostBackTrigger();
asbt.ControlID = lb.ID;
asbt.EventName = "Click";
upPanel.Triggers.Add(asbt);


Good find. That makes sense - although it's peculiar that it works different for the LinkButton and ImageButton. Thanks for posting that.

LinkButton OnCommand UpdatePanel

Somehow, the OnCommand method of a LinkButton never fires in the following code. I believe I'm running the latest of Ajax (1.0) and the Microsoft.Web.Preview.dll is there in my Bin directory. Any clue? I'm pretty sure I got this working when I didn't have UpdatePanel.

.ASPX code:

1<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">2 <asp:ScriptManager ID="ScriptManager1" runat="server">3 </asp:ScriptManager>4 <asp:UpdatePanel ID="up1" runat="server">5 <ContentTemplate>6 <asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="false" Font-Size="X-Small"7 Width="100%" ShowHeader="false" BorderStyle="none">8 <RowStyle BackColor="#ffffff" />9 <Columns>10 <asp:ImageField DataImageUrlField="status" DataImageUrlFormatString="~/Images/{0}.png"11 NullDisplayText=" - " ItemStyle-HorizontalAlign="center" DataAlternateTextField="description" />12 <asp:TemplateField>13 <ItemTemplate>14 <asp:Literal runat="server" ID="appName" EnableViewState="false" Text='<%# Eval("app_name") + " (" + Eval("application_id") + ")"%>'></asp:Literal>15 </ItemTemplate>16 </asp:TemplateField>17 <asp:TemplateField ItemStyle-HorizontalAlign="center">18 <ItemTemplate>19 <asp:LinkButton runat="server" ID="linkPromote" Text='<%# this.GetLink(Convert.ToInt32(Eval("status")))%>'20 Visible='<%# this.ShowLink(Convert.ToInt32(Eval("status")))%>' OnClientClick="Ask();"21 CommandArgument='<%# Eval("application_id") + "|" + Eval("run_date") + "|" + Eval("status")%>'22 CommandName='<%# this.GetLink(Convert.ToInt32(Eval("status")))%>' OnCommand="ChangeStatus" />23 </ItemTemplate>24 </asp:TemplateField>25 <asp:TemplateField ItemStyle-HorizontalAlign="center">26 <ItemTemplate>27 <asp:HyperLink ID="details" runat="server" NavigateUrl='<%# "javascript:MasterList(" + this.GetRowData(Container) + ");"%>'28 ImageUrl="~/Images/more.gif" ToolTip="Details" Visible='<%# this.ShowDetails(Convert.ToInt32(Eval("status")))%>' />29 </ItemTemplate>30 </asp:TemplateField>31 </Columns>32 </asp:GridView>33 </ContentTemplate>34 </asp:UpdatePanel>35 <asp:ObjectDataSource ID="ObjectDataSource2" runat="server" SelectMethod="GetListOfRunningAppsNotCompleted"36 TypeName="AnalyticsBizOb.StatusMonitorImp"></asp:ObjectDataSource>3738 <script type="text/javascript">39 function Ask()40 {41 return confirm('Are you sure you want to change status for this App?');42 }43 </script>4445</asp:Content>

Code-behind:

1protected void Page_Load(object sender, EventArgs e)2 {3if (!IsPostBack)4 {5 PopulateRunningAppsGrid();6 }7 }8void PopulateRunningAppsGrid()9 {10 ObjectDataSource2.SelectParameters.Clear();11 ObjectDataSource2.SelectParameters.Add("runDate","20070419");12 ObjectDataSource2.DataBind();13 GridView2.DataSourceID ="ObjectDataSource2";14 GridView2.DataBind();1516 }17protected void ChangeStatus(object sender, CommandEventArgs e)18 {19if (e.CommandName =="Restart" || e.CommandName =="Promote")20 {21 StatusMonitorImp smi =new StatusMonitorImp();22string[] args = e.CommandArgument.ToString().Split('|');23int statusTo = e.CommandName =="Restart" ? 19 : 20;2425 ScriptManager.RegisterStartupScript(up1, up1.GetType(),"success","alert('Successfully changed the status of app " + args[0] +" from " + args[2] +" to " + statusTo.ToString() +" for date " + args[1] +".');",true);2627 }28 GridView2.DataBind();29 }30public string GetRowData(IDataItemContainer iic)31 {32if (iic !=null)33 {34return DataBinder.Eval(iic.DataItem,"run_date").ToString() +", "35 + DataBinder.Eval(iic.DataItem,"application_id").ToString() +", '"36 + DataBinder.Eval(iic.DataItem,"app_name").ToString() +"'";37 }38else39 return"";40 }41protected bool ShowLink(int status)42 {43if (status == 19 || status == 50 || status == 500)44return true;45else46 return false;47 }4849protected bool ShowDetails(int status)50 {51if (status > 0 && status != 999)52return true;53else54 return false;55 }56protected string GetLink(int status)57 {58string ret ="";59if (status == 500 || status == 50)60 ret ="Restart";61if (status == 19)62 ret ="Promote";63return ret;64 }

Found the reason why it was not working. In my MasterPage, I've turn off the ViewState (EnableViewState = "false"), that's why the code above (OnCommand="ChangeStatus") was not firing up.

I don't know whether it is by design but I think it's bug in ASP.Net and something is not right in the core.

LinkButton OnClick not firing inside UpdatePanel

I have a page with a MultiView containing 2 views. The second view has a number of LinkButtons which implement a menu. I have wrapped the MultiView inside an UpdatePanel. The problem that I am having is that the events (specifically OnClick) don't fire for the LinkButtons. If I replace the LinkButtons with a Button everything works fine. I am doing something wrong or is there a problem with LinkButtons?I'm having the same issue right now. In an earlier version I had this working, so I'm not quite sure what happened.
I looked into it a bit farther and the postback function seems to be missing from the javascript for the page. I switched to MagicAjax and now everything works the way it is supposed to.
I'm a little too deep to make any switches. :-)

hello.

let me see if i understand what's going: you have a multiview control and in one of the views you have several linkbuttons. clicking on the button doesn't postback and from what you say, the problem is that the postback method isn't in the page.

so, i assume that the view that has the buttons isn't the initial view and that you don't have anything on that page that is able to start a postback. if this is your scenario, then the problem you're seeing is a bug of the atlas platform. the problem is that during partial postbacks, the __doPostBack is discarded and isn't added on the client side because the platform assumes that it is alread there.

an easy workaround is to add a button to the page (with the usesubmitbehavior set to false) and hide it (by using the css display property).btw, the reason everything worked with buttons is because on asp.net 2, they are inserted as submit buttons by default (<input type="submit">).


I guess my problem is a little simplier. I have two LinkButton objects inside of a Panel object, which is then contained in an UpdatePanel. To test, I added a Button object and it does postback as expected. The LinkButtons do not postback and I cannot figure out why. Is this a known issue with Atlas?

hello.

it looks like you can reproduce the problem with a simple page...can you post that page here?


The problem was the panel being set to "visible = false" up front. I have a link on the page that sets it to be visible though. Once that link is clicked and the panel is visible, the two LinkButtons don't fire the postbacks. Instead, when I started up with visible being set to true, everything worked just fine. So I just had to do a little z-index magic to get around setting it to "visible = false" to start. Kind of weird I can't start with that panel not being visible.

hello.

well, that's the problem i've described in my previous post. the same thing happens when you put the button inside a panel and set it its visible property to false during the initial rendering of the page. in these cases, when you don't have any other controls that use the __doPostBack method, the page won't work correctly when you use partial postbacks because even though the server side sends the __doPostBack method on the reponse for a partial postback, it'll be discarded by the client framework since it allways assumes that the method was added to the page during its initial rendering.

this is an old bug that i've reported a few months ago, though it still hasn't been solved.


Thank god for this thread, I finally able to solve the problem that I've been trying to solve for days. Your solution does work for panels and/or linkbutton inside the updatepanel. However, when I tried to set the visibility of the panel located outside of the updatepanel to true (initially set to false) by calling a method, it does not work. Any workaround for this? Thanks a bunch!

hello.

are you doing that (changing the visibility of the panel) during a partial postback? if so, then the panel must be inside an updatepanel...


Umm ... well, I don't know .. Am I? Anyhow, this is the code:

<asp:Content ID="Content1" ContentPlaceHolderID="Main" runat="Server"> <cc1:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true"> </cc1:ScriptManager> <div id="comments" class="page"> <table> <tr> <td> <asp:Label ID="Label1" runat="server" Text="Name"></asp:Label></td> <td> <asp:TextBox ID="Nama" runat="server"></asp:TextBox></td> </tr> <tr> <td> <asp:Label ID="Label2" runat="server" Text="Comment" Style="vertical-align: top"></asp:Label></td> <td> <asp:TextBox ID="Komen" runat="server" Height="72px" Width="299px"></asp:TextBox></td> </tr> <tr> <td> <asp:Button ID="Button1" runat="server" OnClick="SubmitComment" Text="Submit" /></td> <td><asp:Label Visible=false ForeColor=red ID=commentError runat=server></asp:Label></td> </tr> </table> <br /> <cc1:UpdatePanel ID="UpdatePanel1" runat="server" Mode="Conditional"> <ContentTemplate> <asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" DataSourceID="SqlDataSource1"> <Columns> <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" /> <asp:BoundField DataField="Comment" HeaderText="Comment" SortExpression="Comment" /> <asp:BoundField DataField="Date" HeaderText="Date" SortExpression="Date" /> </Columns> </asp:GridView> <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString%>" SelectCommand="SELECT Name, Comment, Date FROM Comments ORDER BY Date DESC"></asp:SqlDataSource> </ContentTemplate> <Triggers> <cc1:ControlEventTrigger ControlID="Button1" EventName="Click" /> </Triggers> </cc1:UpdatePanel> </div></asp:Content>
and this is the codebehind that validate the input:

public void SubmitComment(Object sender, EventArgs e) { String dt = DateTime.Now.ToString(); String Name = Nama.Text; String Comment = Komen.Text;if (Name =="" || Comment =="") { commentError.Text ="Please complete all required fields"; commentError.Visible =true; }else {//SOME CODE TO INSERT Name and Comment to database } }
So, basically if the user doesn't put either name or comment, the commentError label will be shown up. Should I just put the entire table into update panel? Because when the Button1 is not tied up to the triggers, everything works fine.

hello.

well, that's because when button1 is configured as a trigger, the client portion of atlas intercpets the call and performs a partial postback; when you don't do that, you get a full postback. so, you have 2 options: you can put everything inside a panel or you can use two panels.

LinkButtons programmically added to updatepanel click event not firing

I have a conditional updatepanel with a multiview control inside. The first view displays a list of items in a table with a linkbutton next to each one created programmically with an eventhandler for the click event. The click event changes the multiview's active view to the next view to display controls for editing that item. The item table's content is first initialized in the OnLoad() function inside a if(!isPostback). I plan to eventually have a save button in the second view that will update the table's content after that. (ScriptManager EnablePartialRender = "true").

Ex:

    for(int i = 0; i < itemcount; i++) { ... LinkButton itemedit = new LinkButton(); itemedit.Text = "Edit"; itemedit.Click += new EventHandler(itemedit_Click); table.Controls.Rows[i].Cells[1].Add(itemedit); ...}

When I view the page and click the linkbutton next to one of the items in the updatepanel it starts to update. However, the view never changes. Further tests have shown that the click event is never being handled. If I change the code so that the table is updated during initial load and postbacks, I can get the click event to fire once. After the multiview is goes back to the original view, the click event can no longer be raised until the whole page is reloaded.

So, what I am trying to figure out is how to create eventhandlers at runtime inside an updatepanel and getting them to fire on an update.

Well, I have found a solution. I desided to scale the problem down to the most basic functions by creating a test application containing an updatepanel, multiview control with two views, and some code in the background to create a linkbutton to switch from one view to the other. The page looks like this as generated by VS:

<%@. Page Language="C#" AutoEventWireup="true" CodeFile="dynamicevent.aspx.cs" Inherits="dynamicevent" %
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
<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 ID="ScriptManager1" runat="server" EnablePartialRendering="True">
</atlas:ScriptManager>

</div>
<atlas:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:MultiView ID="MultiView1" runat="server" ActiveViewIndex="0">
<asp:View ID="View1" runat="server">
view1</asp:View>
<asp:View ID="View2" runat="server">
view2</asp:View>
</asp:MultiView>
</ContentTemplate>
</atlas:UpdatePanel>
</form>
</body>
</html>

The page is pretty basic and so is the code behind:

public partialclass dynamicevent : System.Web.UI.Page{protected void Page_Load(object sender, EventArgs e) { LinkButton button =new LinkButton(); button.Text ="switch"; button.Click +=new EventHandler(button_Click);this.View1.Controls.Add(button); }void button_Click(object sender, EventArgs e) {this.MultiView1.ActiveViewIndex = 1; }}

This code creates one LinkButton to switch from ActiveViewIndex=0 to 1 and it works just fine. However, on a larger scale, creating a hundred or more LinkButtons next to records that must be requested from a database each time the page handles a postback doesn't sound like a good idea to me. So, I moved by button creation code into an if(!IsPostBack) block:

protected void Page_Load(object sender, EventArgs e) {if (!this.IsPostBack) { LinkButton button =new LinkButton(); button.Text ="switch"; button.Click +=new EventHandler(button_Click);this.View1.Controls.Add(button); } }
The changes break the page. When I click the LinkButton, the updatepanel reloads the contents of the first view minus the linkbutton. The linkbutton is lost and its eventhandler with it. So, perhaps atlas requires that everything remain wired up perfectly up until after Page_Load() is called at least. I did some thinking and came up with some code that fixes the problem by using the cache to store the button to be rewired on the next postback. It appears that that is all the work I need to do to get my click handler to work. I think the benefits are significant enough although it is hard to see in this example: protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
LinkButton button =new LinkButton();
button.Text ="switch";
button.Click +=new EventHandler(button_Click);

this.View1.Controls.Add(button);
Cache.Insert("test", button);
}
else
{
((LinkButton)Cache["test"]).Click +=new EventHandler(button_Click);
this.FindControl(((LinkButton)Cache["test"]).Parent.UniqueID).Controls.Add(((LinkButton)Cache["test"]));
}
}

The code rewires the event handler during a postback. The Control.Parent .Controls.Add() does not work directly for the LinkButton in the cache but the FindControl() method works just fine. I believe that although they have the same name, the first parent of the LinkButton is not the same as the second one. I am new to ASP.NET v2 and Atlas but I do not remember coming across this problem in the past with .NET 1.1.

If anyone has a better solution, please let me know. At this moment I am facing writing some manager class to wire up all my eventhandlers on on each postback and I really would like a better way.


changed

this.FindControl(((LinkButton)Cache["test"]).Parent.UniqueID).Controls.Add(((LinkButton)Cache["test"]));
to
this.Controls.Add(((LinkButton)Cache["test"]));
and it works just fine. This means that it does not matter where the LinkButton is located, just that it is added back to the page.

Thanks a lot for the solution you posted. I have been facing the same problem and your solution worked for me. But, I wonder if there is some other solution to this issue. If I find any I will post it here.

Thanks again.


Yes, that's not specific to Atlas. Any control that's added dynamically to the control tree must be added back on every subsequent postback.

I came across another issue when I was working with this yesterday. What I saw was that after a few postbacks my dynamically added link buttons won't work in fact it threw an object required error. Reason, they were removed from the cache and hencethis.Controls.Add(((LinkButton)Cache["test"])); would not work.

So, I tried to check if the cache had the button in it and only then I would execute this statement else I would create new linkbuttons. But guess what, I got back to the same problem I started off with. The button would not fire the event.

In the solution we completely depend on the cache to make sure that the linkbuttons are wired to the respective events. What would happen when the buttons are removed from the cache for whatever reason, especially in a production environment?


Ok, I think I may have a solution for this...as bleroy indicated this is the default behavior with dynamically added controls (that you have to add them to the page on every postback). So, if you add the linkbuttons to the page on Page_Init instead of Page_Load, you will not have to worry about caching them in order to re-wire the controls with the events.

Let me know if this was helpful.


I'd like to respectfully point out that putting a control in the cache is a bad, bad, bad idea and you should never ever do it. One reason is that this maintains an in-memory reference to the instance of the control, hence to the corresponding instance of the page and thus to a huge object graph that should have been thrown away at the end of the request. There is no way this is not going to blow up whenever you get more than a few simultaneous requests.

You should only put data (that is, disconnected data) or output (i.e. strings) in cache...

List Box and the update panel

I would like to know the event name to use when an ASP List Box is used with the update panel control. I would like the updatePanel to fire when the ListBox Selected Index Changed event occurs.

Thank You for any help

George

<asp:ListBoxID="ListBox1"runat="server"DataSourceID="AccessDataSource1"DataTextField="product_name"DataValueField="product_id"Rows="30"CausesValidation="True"></asp:ListBox>

<asp:AccessDataSourceID="AccessDataSource1"runat="server"DataFile="~/App_Data/test.mdb"SelectCommand="SELECT [product_id], [product_name] FROM [Products]"></asp:AccessDataSource>

<asp:ButtonID="Button1"runat="server"Text="Button"/>

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

<Triggers>

<atlas:ControlEventTriggerControlID="ListBox1"EventName="SelectedIndexChanged"/> <!-- DOES NOT FIRE -->

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

</Triggers>

<ContentTemplate>

<asp:LabelID="Label2"runat="server"Text="Labe354"></asp:Label>

</ContentTemplate>

</atlas:UpdatePanel>

You have everything exactly right, though it might not actually be what you want. Every time the SelectedIndexChanged event is raised, or the button is clicked, the UpdatePanel will be updated. However, to get any of that to happen, a postback must occur. In your sample page, the only way to get that to happen is to click the button. To make the page update immediately when the list selection changes, add this property to your ListBox: AutoPostBack="true"

Thanks,

Eilon

Monday, March 26, 2012

ListBox does not preserve selected items after using UpdatePanel

Hi there,

I have a ListBox with Multiple Selection feature. After I click the Button on the form, I should process the selected items in the ListBox. The code works fine but after I add the ListBox in an UpdatePanel, it does not preserve selected items.

Any suggestions?

Thanks,
Mosh

use hidden fields.
function addItemstoHiddenField(){
var lbPlantDest = document.getElementById("lbPlantDest");
var lbSalesDest = document.getElementById("lbSalesDest");
var lbPlantDest = document.getElementById("lbPlantSrc");
var lbSalesDest = document.getElementById("lbSalesSrc");
var hdnPlantAccess = document.getElementById('hdnPlantAccess');
var hdnSalesAccess = document.getElementById('hdnSalesAccess');
var hdnPlantAccess = document.getElementById('hdnSrcPlantAccess');
var hdnSalesAccess = document.getElementById('hdnSrcSalesAccess');
for (i = lbPlantDest.options.length - 1; i >= 0; i--) {
hdnPlantAccess.value = hdnPlantAccess.value + lbPlantDest.options[i].value + ',';
}
for (i = lbSalesDest.options.length - 1; i >= 0; i--) {
hdnSalesAccess.value = hdnSalesAccess.value + lbSalesDest.options[i].value + ',';
}
for (i = lbPlantSrc.options.length - 1; i >= 0; i--) {
hdnSrcPlantAccess.value = hdnSrcPlantAccess.value + lbPlantSrc.options[i].value + ',';
}
for (i = lbSalesSrc.options.length - 1; i >= 0; i--) {
hdnSrcSalesAccess.value = hdnSrcSalesAccess.value + lbSalesSrc.options[i].value + ',';
}
}

ListBox error with UpdatePanel

Using a listbox in an update panel with visible= false and AutoPostBack=true causes an error in the foloiwng code below. If I remove either the AutoPostBack and instead use a button to PostBack it works fine or if I remove the Visible it works fine. My workaround is to set the style of the listbox to display:none instead of using Visible.

I'm using the June CTP

<formid="form1"runat="server">
<atlas:ScriptManagerID="scriptManager"runat="server"EnablePartialRendering="true"/>
<div>
<atlas:UpdatePanelID="upListBox"runat="server">
<ContentTemplate>
<asp:ButtonID="Button1"runat="server"Text="Button"OnClick="AddListItems"/>
<asp:ListBoxID="ListBox1"runat="server"OnSelectedIndexChanged="ListBox1_SelectedIndexChanged"Visible="false"AutoPostBack="true">
<asp:ListItemText="one"/>
<asp:ListItemText="two"/>
<asp:ListItemText="three"/>
</asp:ListBox>
</ContentTemplate>
</atlas:UpdatePanel>
</div>
</form>

CODEBEHIND

publicpartialclassDefault2 : System.Web.UI.Page
{
protectedvoid ListBox1_SelectedIndexChanged(object sender,EventArgs e)
{
ListBox1.Visible =false;
}

protectedvoid AddListItems(object sender,EventArgs e)
{
ListBox1.Visible =true;
}
}

Hi,

there's an issue with the UpdatePanel and the __doPostBack function that prevents it to be injected on the page if it is required by a control inside an UpdatePanel.

The solution is to force the server to drop the __doPostBack function. Add this statement in the Page_Load method:

Page.ClientScript.GetPostBackEventReference(this, String.Empty);

listbox in updatepannel takes to long

Hello, I have an updatePanel and inside of it i have textbox, listbox and div. And it all works perfecly if in the listbox i have to 100 rows. But in few cases i have arround 6000 rows. The problem occures when i select a row from the lisbox with 6000 rows and I'm tryning to put some message into the Div. It assignes the InnerHtml of the div and waits for about 1 minute with 100% processor activity and then it displays the div content. How can i shorten this time? Any sugestions?

Thanks

The UpdatePanel passes the ViewState for the whole page each time you do this, not to mention it sounds like 6000 records are being rebound. Remember the whole UpdatePanel needs to update... A better approach would to be use something like PageMethods to get the message (seehttp://encosia.com/index.php/2007/07/11/why-aspnet-ajax-updatepanels-are-dangerous) and then fill the DIV client-side.

-Damien


See the following thread and side threads for a long discussion of the problem and code that will cut the update time to milliseconds if your listbox is simple.

http://forums.asp.net/p/1065352/1540804.aspx

There are other ways of doing it as Damien suggested, but most of them involve the PageRequestManager (http://www.asp.net/AJAX/Documentation/Live/ClientReference/Sys.WebForms/PageRequestManagerClass/default.aspx) as the best solution.


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


Actualy I solved it with this link:

http://encosia.com/index.php/2007/07/13/easily-refresh-an-updatepanel-using-javascript/

listbox ondblclick attribute

Hi

I am trying to invoke a listboxes double click attribute to utilize the Ajax.Net functionality.

I have a listbox in an UpdatePanel, and using the OnSelectedIndexChanged event I successfully perform client side actions using Ajax.
I now want to perform an action when a user double clicks on an item of the listbox. (remove this item)

I tried copying the OnSelectedIndexChanged attribute value generated by dot net and adding it through the code:

lbMyListBox.Attributes.Add("ondblclick","javascript:setTimeout('__doPostBack(\\'DoubleClick\\',\\'\\')', 0)");

This however keeps causing a page post back.
Is it possible to use the double click attribute?
I have searched everywhere without much luck

TIA

You will need to subclass the ListBox control and create the ondblclick event for postback usage... and remove the existing onSelectedIndexChanged event. This topic deals with fairly advanced .Net web control programming.

Here's an example that is quick and dirty... and does not fully take care of all possible scenarios.

public class MyListBox : ListBox, IPostBackEventHandler, IPostBackDataHandler {public event EventHandler OnDoubleClick;#region IPostBackEventHandler Membersvoid IPostBackEventHandler.RaisePostBackEvent(string eventArgument) {if (eventArgument =="ondblclick") {if (OnDoubleClick !=null)this.OnDoubleClick(this, EventArgs.Empty); } }#endregion protected override void OnPreRender(EventArgs e) {base.OnPreRender(e);this.Attributes.Add("ondblclick", Page.ClientScript.GetPostBackEventReference(this,"ondblclick")); }protected override void Render(HtmlTextWriter writer) {//Here we will remove the onchange event through string manipulation. StringWriter sw =new StringWriter(); HtmlTextWriter newWriter =new HtmlTextWriter(sw);base.Render(newWriter); sw.Flush();string html = sw.ToString();int indexofOnChg=html.IndexOf("onchange=\""); sw.Close(); html = html.Remove(indexofOnChg,html.IndexOf(" ", indexofOnChg) - indexofOnChg); writer.Write(html); } }

Thanks for your advice

Will give it a wirl

Saturday, March 24, 2012

ListView vs. UpdatePanel with GridView

I am curious - which is the 'better' approach?

It appears with the listview and itemview you can accomplish much of what the gridview does.

Is there a performance difference?

On a side note - I hope to get some designer support for the listview/itemview/navigation/sorting - something similiar to the listview where you can create item templates - specify data columns from the datasource, etc...

hello.

i guess you'll just have to measure it :) i guess that using a gridview will be easier but you should take into account that when the contents of a panel are refreshed, everything is sent back to the server (this might be the sabe thing as doing a complete postback!)...

Literal nested in UpdatePanel error: "Object reference not set to an instance of an object

I am trying to set the content of a literal which is nested inside an UpdatePanel. But when I try to reference the Literal control, I get this message: "Object reference not set to an instance of an object." This despite the fact that the name shows in Intellisense. Actually, not entirely true. It sometimes isn't showing in Intellisense, for reasons I can't fathom. But I'm not getting a compilation error, so I assume it does recognise the name, but for some reason the object is null. Here's the code:

 <asp:UpdatePanel runat="server" ID="UpdatePanel1" EnableViewState ="true" Visible="true" RenderMode="Block" UpdateMode="Conditional"> <asp:ContentTemplate> <div style="width:350px; height:400px" class="newscontent"> <asp:Literal runat="server" ID="litContent"></asp:Literal> </div> </asp:ContentTemplate> </asp:UpdatePanel>

C#:

protected void Refresh(Object Sender, RepeaterCommandEventArgs e) {if (e.CommandName=="GetContent") {int id = Convert.ToInt32((e.CommandArgument)); ObjectModel.News item =new ObjectModel.News(id); litContent.Text = item.Content; litContent.Text += DisplayDocuments(id); UpdatePanel1.Update(); } }
The Refresh function is triggered by the user clicking on a LinkButton in a repeater, but this is irrelevant to the problem, since I get the same error message if I put a simple line of code in the page load function to set the text property on the the literal.

just yesterday got same problem with accordion control and textbox

spend about 3 hours here how it goes :UpdatePanel1 onpage load or on page init try this code

///////////////////////////////////////////////////////////////////////////

Literal litContent=newLiteral();

litContent= UpdatePanel1.FindControl ("litContent") asLiteral;

////////////////////////////////////////////////////


Sol90046:

just yesterday got same problem with accordion control and textbox

spend about 3 hours here how it goes :UpdatePanel1 onpage load or on page init try this code

///////////////////////////////////////////////////////////////////////////

Literal litContent=newLiteral();

litContent= UpdatePanel1.FindControl ("litContent") asLiteral;

////////////////////////////////////////////////////

Thank you! This worked as far as eliminating my error message went. But even though the code now appears to be doing what it is told, i.e., I can step through it in debug mode and the text property of the Literal is being set to the correct content, the update panel is not displaying the results. It also appears to be doing a full page refresh rather than a partial one. I do have a scriptmanager on the page with EnablePartialRendering set to true.

Load a javascript file in an updatepanel

Ipresent the context to you. I have a project principal compound of anupdatepanel. When I click on a button, I filled my updatepanel with a"templatd control". This one appears well. This control haves embeddes resources (images + Javascript file). My problem is that my control charges only the images and not my Javascript file. When I use this control in a simple page, it works correctly. I think that it is impossible to charge a fileJavascript in a updatepanel. What do you think about it? Thank you inadvance for your answers.

Damien

Damien,

Personally what I would do as UpdatePanel makes a server request to do your processing in the postback server side, easier and cleaner, you already in the server, then why not. Putting javascript with the UpdatePanel, why? the UpdatePanel is to go to the server without the user to see the request, then just use that!

Makes sense?

Load in-line javascript functions after UpdatePanel refresh

I have a lot of user controls that have in-line javascript functions specific to the content of the user control, validations and automated reactions. This javascript is written mostly by client side developers. Is there any way to allow them to keep writting their in-line javascript on the user controls, but still have that javascript be active after an updatepanel conditionally makes the user control visible? For example imagine a page with a button and the user control. The user control is in an update panel tiggered by the button click. When clicked the user control has its visibility set to true and the user interacts with the newly visible controls contained within. Because the user control was initially in an update panel, the original page source does not contain the in-line javascript functions so they are never evaluated by the browser. In order to keep the client side group's functionali i've had to recreate the client side code on the server side by building a large string that references controls using the control.ClientID property (just like the client side group does with inline scriplets $get(<%= control.ClientId %>) and then registering this string on the page with ScriptManager. This is too inefficient a process and having the javascript placed on every page that uses the user control seems counter productive with regard to user controls. Placing all the javascript in external files that get loaded by ScriptManager is also not an option as the javascript is often control specfic. Is there no way to get the browser to recognise the in-line javascript after an update panel loads it? Is this something that is planned for the future if not?

Well, I don't know if it is the final solution, but I figured that I could use display:none and display:block on a panel wrapping the user control instead of using the Visible property on the control itself. This way the control (and most importantly the javascript) is initially rendered, but not browser visible. If there is still some way to use the built in Visible property to do what I want, please let me know. I like that the inital page load using the Visible property doesn't have the extra weight of controls that are not usuable.


You can give this approach a try:http://blogs.msdn.com/sburke/archive/2007/06/13/how-to-make-tab-control-panels-load-on-demand.aspx

-Damien


I believe that approach will suffer from the same issue. The tabcontainer content will not be initially visible and so any inline javascript contained in a tabcontainer will not be evaluated by the browser.


Sorry about that I miss read your question. If the JS is embedded in the usercontrols they need to be loaded, so your solution works. I'm a bit confused why you need the JS loaded if they are control specific. Sounds like there may be a design problem with your solution.

-Damien

Load Page Into UpdatePanel

Hi,

I have a webpage that has a column of links. Each links leads to another webpage. What I want to happen is instead of going to a different webpage, for each of the links, I want an UpdatePanel to be updated with the contents of the target of the links.

So basically I need an update panel with multiple triggers and the update panel has to know which link was clicked so that it knows which page to load.

How would I go about doing this? Thanks in advance.

Przemek

I'd suggest looking into using an iframe for your content instead. Performance would be better, it would be more simple to code/maintain, and I really can't think of any disadvantages.

Wednesday, March 21, 2012

LoadControl and UpdatePanel

hi all,

I am having problems with server controls placed inside an UpdatePanel. they are placed in an acsx (web control) and I am loading them (following instructions encoded in an XML) using LoadControl. but, the inside controls are null.

I am quite sure I've got the page lifecycle messed up somehow. here's a detailed description of what I am doing:

I have got a web control named Canvas (as it is supposed to hold other controls, as well as other Canvases). it has got an UpdatePanel with a PlaceHolder in the ContentTemplate.

I have embedded one Canvas (obviously called Root) in my aspx page, which has the ScriptManager in it.

in the Page_Load event of the original aspx page (I tried Page_PreInit as well, doesn't work) I am dynamically creating other Canvases (by LoadControl) and adding it in my PlaceHolder. I have a method that takes an XML and I am calling that method. it works fine for the root.

however, after I have loaded my control, I call the XML accepting method (with a child XML node) of the newly created control. this is where it gets stuck with a null exception. so it's right after the LoadControl call.

I hope I haven't made a trivial mistake. I removed my UpdatePanel and it works just fine. so it can't be terribly wrong! I am using the January CTP.

cheers.

help! somebody? anybody?

I had the same issue and I just resolved it. You need to add an ID to your control... then it will persist on postbacks. That's all you do (and always create the control in the page_load event). Here's my code and it works like a champ and I'm using MS's AJAX panels as well.

i'm placing a unique control on the page based on the tab they are on but you could just add a single control here as well. Don't worry about the LoadData, those are just methods that load my data into the controls.

Good luck!

protected void Page_Load(object sender, EventArgs e) { LoadPageViewData(radCategoryTabStrip.SelectedIndex); }
private void LoadPageViewData(int index) {//-- clear out the controls pageDynamic.Controls.Clear();string guid = String.Empty;if (lblDetailData.Attributes["GUID"] !=null) { guid = lblDetailData.Attributes["GUID"].ToString(); }switch (index) {case 0://-- create the control CustomControls_Group_Edit oCtrlGroupItemEdit = (CustomControls_Group_Edit)LoadControl("~/CustomControls/Group/Edit.ascx");//new CustomControls_Group_Edit(); //-- wire up the event handler, this way we'll get notified when the control //-- save's it's data and we can update the tree on this page. oCtrlGroupItemEdit.GroupItemSaved +=new EventHandler(itemSaved);//-- give it an id, that way the page_load event will know to rebind it //-- to the same instance on postbacks and persist the data //-- (read an article about it and it works) oCtrlGroupItemEdit.ID ="GroupEdit1";//-- add the control to the page before we invoke the first method multiPage.PageViews[0].Controls.Add(oCtrlGroupItemEdit);//-- load the data oCtrlGroupItemEdit.LoadData(guid);break;case 1://-- not doing any custom events for this one, so just load the control CustomControls_Groupings_ProductList oCtrlProductList = (CustomControls_Groupings_ProductList)LoadControl("~/CustomControls/Groupings/ProductList.ascx");//-- add the control the page before we invoke the first method oCtrlProductList.ID ="ProductList1"; pageDynamic.Controls.Add(oCtrlProductList);//-- this must be called after it's added to the control collection (not before or it will fail) oCtrlProductList.LoadData(guid);break;case 2:break;case 3:break; }//-- make sure this control is selected pageDynamic.Selected =true;//-- either works: multiPage.PageViews[0].Selected = true; //-- update the ajax panel updatePanelCategoryInfo.Update(); }

LoadControl issue with UpdatePanel ?

Hi,

I have a very strange problem. I'm trying to decrease traffic on a web application. To do so, i'm adding some UpdatePanel in some user controls of our app.
No problem with the first controls i modified. I had the behaviour not modified while trafic was much better.

But i have a problem with the last control. I added some update panels on it (more than with the others). Finally, there are 14 Update panels in my user control (may be one of the most complicated in this application). The user control is loaded dynamically (using LoadControl), and it worked without problem before i added the update panels. After that, the LoadControl doesn't even call the OnInit() event, and directly goes to the CreateChildControls (where the controls are not then initialized.

I have found no information about such a problem. Does anyone have information about this kind of problem ? Is there a known issue on UpdatePanel about this?

thanks for your help.
Guillaume

Hi,

I think this is an old question,It is something about Dynamicaly loading User Controls into UpdatePanel.

You can see the following threads too:

http://forums.asp.net/p/1156704/1906671.aspx#1906671

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

Best Regards,


Thanks for your answer.

Unfortunately, this is not where my problem is. I repeat that i have my original control, already dynamically loaded, wich works fine.

This is only after adding all update panels (I know this is too much, but i do what i can with what i have) that controls inside my dynamically added control are not initialized (variables are null) and the first event called on the control is CreateChildControls... Any idea about the source of my problem? For me, it's like if there were a limit number of UpdatePanel... but it may be something else. I have no idea and found no resource on this problem (that's why i posted)...

Thanks


Hi,

If you dynamically add your usercontorl into an updatepanel, the issue comes.

Good luck!


See this

http://geekswithblogs.net/rashid/archive/2007/08/11/Loading-UserControl-Dynamically-in-UpdatePanel.aspx


Thanks for your answers. I finally managed to do what i wanted. The issue seems to be due to the use of Triggers. When i removed the triggers (and made the work programmaticaly), it fell working :).

I think there's a problem with triggers though :(.

loading an aspx page in ajax updatepanel

Is there a way to load an aspx page in the updatepanel or into a ajax tabcontainer control? Please advise

The only way that I have heard of is using iFrames, but we haven't used that because either page transitions don't matter to us or end up using a different technique to change the content in a particular area of the page (it depends on the page).