Showing posts with label linkbuttons. Show all posts
Showing posts with label linkbuttons. 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 in a DataList is shown incorrectly

I use a DataList to show LinkButton′s (CommandName="Select") of which the names are read from a database. That part works nice.

ItemTemplate : LinkButtons on a white background with brown text
SelectedItemTemplate : LinkButtons on a brown backgound with white text

The strange behaviour when I click a LinkButton:

    the click event routine works okaywhen I click the first time a button, its is shown incorrectlySadthe button text is shown still in brown on a white backgrounda brown border is shown arround the buttonwhen I click the same button again it is shown correctlySmilethe button text is shown in white on a brown backgrounda brown border is shown arround the button

Does somebody has an idea what is happening here?

<asp:ScriptManagerID="ScriptManager1"runat="server"></asp:ScriptManager>
<asp:UpdatePanelID="UpdatePanel1"runat="server">
<Triggers>
<asp:AsyncPostBackTriggerControlID="DataListGrupos"EventName="SelectedIndexChanged"/>
</Triggers>
<ContentTemplate>
<asp:DataListID="DataListGrupos"runat="server"DataKeyField="IdGrupo"DataSourceID="SqlDataSourceGrupos" RepeatColumns="8"CellPadding="5"RepeatLayout="Table"SelectedIndex="0"ShowFooter="False"ShowHeader="False">
<ItemTemplate>
<asp:LinkButtonID="LinkButtonGrupo"runat="server"BackColor="White"CommandName="Select" Font-Bold="True"Font-Names="verdana"Font-Size="Larger"ForeColor="#C04000"Font-Underline="True"Text='<%# Eval("Grupo") %>'></asp:LinkButton>
</ItemTemplate>
<SelectedItemStyleBackColor="#C04000"/>
<SelectedItemTemplate>
<asp:LinkButtonID="LinkButtonGrupo"runat="server"BackColor="#C04000"CommandName="Select"Font-Bold="True"Font-Names="verdana"Font-Size="Larger"ForeColor="White"Text='<%# Eval("Grupo") %>'></asp:LinkButton>
</SelectedItemTemplate>
<ItemStyleBackColor="White"/>
</asp:DataList>
</ContentTemplate>
</asp:UpdatePanel>

Idea For the time being I have bypassed the problem to have at least the result I wanted:

ProtectedSub DataListGrupos_SelectedIndexChanged(ByVal senderAsObject,ByVal eAs System.EventArgs)Handles DataListGrupos.SelectedIndexChanged

Dim MyButtonAs LinkButton

MyButton =CType(Me.DataListGrupos.Items(Session("PreviousGrupoIndex")).FindControl("LinkButtonGrupo"), LinkButton)
MyButton.BackColor = Drawing.Color.White
MyButton.ForeColor = Drawing.Color.FromArgb(&HC04000)
MyButton.Font.Underline =True

MyButton =CType(Me.DataListGrupos.SelectedItem.FindControl("LinkButtonGrupo"), LinkButton)
MyButton.BackColor = Drawing.Color.FromArgb(&HC04000)
MyButton.ForeColor = Drawing.Color.White
MyButton.Font.Underline =False

Session("PreviousGrupoIndex") =Me.DataListGrupos.SelectedIndex
...

EndSub

Linkbutton in asp:reapeater - all in user control, needs to register linkbuttons with ajax

I have a master page with the ajax script manager on it.

the master page then has a user control, which contains an asp:repeater which renders asp:LinkButtons on the page, i need them to be registered with the script manager so that they will only cause page re-renering in the content.

The problem i am facing is getting access to the ScriptManager in the master page fron theRepeater1_ItemCommand event in the user control.

Any thoughts, THanks

To programmatically access the scriptmanager:

Dim sm as ScriptManager
sm = ScriptManager.GetCurrent(Page)

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 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 in a TabContainer lose the active tab

Hi, I have a tabcontainer with a couple of panels. If I have a Button in each panel then clicking the button posts the page back and the tab panel I was in remains active/visible. BUT if I put a link button in Panel 2 and click that then the tabcontainer resets to the first panel.

Here is a simple example:

<cc1:TabContainer ID="TabContainer1" runat="server">
<cc1:TabPanel ID="TabPanel1" runat="server" HeaderText="tab 1">
<ContentTemplate>
<asp:Button runat="server" ID="Button1" Text="postback 1" />
</ContentTemplate>
</cc1:TabPanel>
<cc1:TabPanel ID="TabPanel2" runat="server" HeaderText="tab 2"> <ContentTemplate>

<asp:LinkButton runat=server ID=lnk1>postback from panel 2</asp:LinkButton>
</ContentTemplate>
</cc1:TabPanel>
</cc1:TabContainer>

If I put a button in panel 2 as well as the linkbutton then I get the same thing, BUT if I click the Button first then clicking the link button does not cause the tabcontainer to reset. Which seems to suggest that AJAX is using a button event in some way, but not a linkbutton.

This is causing me a major headache as I have already designed the UI and coded all the DB and middle-tier code, wiring the UI up was supposed to be the easy bit!Wink

Hoping someone can help

Andrew

This problem has been logged with the AJAX Control Toolkit developers as an issue and a workaround is detailed here:http://forums.asp.net/thread/1550723.aspx (basically wrap the tabcontainer in an update panel so that the non-Button postbacks get routed through the AJAX async handlers)

linkbuttons in accordionpane header

I am using an accordion that is created dynamically for a menu and have it working as I want - with one exception. When the user clicks on a dynamically created link button on the header, I want to redirect to another page WITHOUT triggering the default action of the accordionpane (expanding or collapsing). Is there any way to accomplish this? Currently, it triggers the default action of the accordionpane (expands or collapses it) then redirects.

Hi,

The expand/collapse action is fired by the <div> element that the header is wrapped in.

When you click in anywhere in the header, it's fired.

When you click on an element in the header, the element's click will be bubbled up to its parent( the header div ) , thus default action is fired too.

So, you can use javascript to prevent the LinkButton to bubble up the event to prevent this from happening.

The following code snippets help to illustrate my idea.

<script type="text/javascript">
function doSomething(e)
{
if (!e) var e = window.event;
e.cancelBubble = true;
if (e.stopPropagation) e.stopPropagation();
}

</script>

<ajaxToolkit:AccordionPane ID="AccordionPane1" runat="server" HeaderCssClass="myclass">
<Header>
<a href="http://links.10026.com/?link=">1. Accordion</a><asp:LinkButton ID="LinkButton2" runat="server">LinkButton</asp:LinkButton>
</Header>

protected void Page_Load(object sender, EventArgs e)
{
LinkButton2.Attributes.Add("onclick", "doSomething();");

}

Hope this helps.

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