Wednesday, March 28, 2012

Line 5909 Javascript Error

Error Message:

Line:5909
Char:12
Error: Sys.ArgumnetUndefinedException:Value cannot be undefined. Parameter name:id

Code:

I write an mask customer validator control And use this control in ajax updatepanel control. It will show javascript error.

Below is my code:

maskedVad.ClientValidationFunction = this._CallbackFailFunction;
vce4Mask = new ValidatorCallbackExtender();
vce4Mask.TargetControlID = maskedVad.ID;
vce4Mask.HighlightCssClass = this._HighlightCssClass;
vce4Mask.CallbackFailFunction = this._CallbackFailFunction;
vce4Mask.CallbackControlID = this.ID;
Controls.Add(vce4Mask);

This is apparently a bug in the Ajax RTM that will be fixed. In the meantime you should check out this link for a solution:
http://blogs.msdn.com/mattgi/archive/2007/01/23/asp-net-ajax-validators.aspx


I replaced validators.js file and added the tagmapping in web.config. but the bug still existed. Can someone give me more suggestions?


Hi Wallance,

To troubleshoot this issue, we really need the source code to reproduce the problem, so that we can investigate the issue in house. It is not necessary that you send out the complete source of your project. We just need a simplest sample to reproduce the problem. You can remove any confidential information or business logic from it.

Best Regards,

Jonathan


I do a custom extendtextbox webcontrol.

TextBox txt = new TextBox()

req = new RequiredFieldValidator();
req.ControlToValidate = this.ID;
req.ID = this.ID + "_req";
req.Display = ValidatorDisplay.None;
string sRoot = HttpContext.Current.Request.ApplicationPath;
req.ErrorMessage = this.RequiredErrorMsg;
req.EnableClientScript = (this.ClientScript.ToLower() != "false");
Controls.Add(req);

vce4Required = new ValidatorCallbackExtender();
vce4Required.TargetControlID = req.ID;
vce4Required.HighlightCssClass = this._HighlightCssClass;
vce4Required.CallbackFailFunction = this._CallbackFailFunction;
vce4Required.CallbackControlID = this.ID;

See the aspx

<asp:UpdatePanel ID="UpdatePanel" runat="server" UpdateMode="Conditional">
<contenttemplate>

<asp:Table runat="server" id="appInfoTable">
</asp:Table>

</contenttemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnadd" EventName="Click" />
</Triggers>


</asp:UpdatePanel>

addbtn_click

protected void CreateRows(int Rowcount)
{
int i = 0;
for (i = 0; i < Rowcount; i++)
{
TableRow tr = new TableRow();

TableCell tc = new TableCell();
extendtextbox txt = CreateTextBox(i);
tc.Controls.Add(txt);

tr.Cells.Add(tc);
appInfoTable.Rows.Add(tr);
}
}

private extendtextbox CreateTextBox(int loop)
{
extendtextbox txtbox = new extendtextbox ();
txtbox.Validate = "required";

txtbox.ID = "mytextbox" + loop.ToString();
txtbox.Label = "acc_accountInfoForm_label_loginInfo";
txtbox.RequiredErrorMsg = "only for test";
txtbox.Type = extendtextbox .Text;
return txtbox;
}

Because the code is very long. Include one webcontrol and one page.

Thank you very much.


Hi Wallance,

Please add break point at "req = new RequiredFieldValidator(); req.ControlToValidate = this.ID;" and debug it step-by-step since the error propmt is "Sys.ArgumnetUndefinedException:Value cannot be undefined. Parameter name:id". Thanks.

Best Regards,

Jonathan.

Line break problem in ASPNET AJAx


I am using ASP.NET AJAx 1.0 Framework.

The page is diplayed perfectly first time. But after a asynchronous post back an extra line added between the Header and the user control.

And no Styling related operations are done in the postback call.

I have compared the HTML that is generated before and after the call. But both are identical.

And I think the reason is that we cant see the modification made by the Ajax Asynchonous calls to the HTML file at the client side.

Does it possible to see the modified HTML code in the browser after a Ajax call to the server?

I don't know the exact solution to your problem, but, If I were you, I would use Fiddler

http://www.fiddlertool.com/

to see what's going on. Fiddler is an excellent HTTP debugging proxy, that monitors each and everyone HTTP request.


Fiddler's good for seeing the reqeust/response. IE Dev toolbar or Firebug are essential for seeing the 'live' DOM.


And this line break problem appears only in IE. Its working fine in Firefox 1.5.


Hi,

There are some useful tools in our daily development work.Such as:

IE: Fidder、IE Dev Toolbar、Instance source、HttpWatch、Web Development Helper(especially for UpdatePanel)

Firefox: Firebug

Hope it helps!

Linebreak appears after update panel submits

I wrote a control that would allow a user to click on a label, and then edit it the value, and send back the new value to the server via an update panel.

However, the first time the value is sent to the server, a line break appears right above the text box, i dont think this is a css error, i can't seem to figure out what is causing it by examining the DOM. This only appears in IE, not Firefox, Any ideas?

Here's the mark up for the Control

<%@dotnet.itags.org. Control Language="VB" AutoEventWireup="false" CodeFile="QuickEditLabel.ascx.vb" Inherits="QuickEditLabel" %><script type="text/javascript"> function<%=Me.hidCurrentFileId.ClientID%>updateNumber(param) { var hiddenField = document.getElementById("<%=hidCurrentFileId.ClientID%>"); hiddenField.value = param; __doPostBack('<%=hidCurrentFileId.ClientID%>',''); } function QuickEditSwap(hideMe, showMe) { showMe.style.display = 'none'; hideMe.style.display = 'inline'; }</script><asp:HiddenField ID="hidCurrentFileId" runat="server" Value="" /><asp:UpdatePanel ID="updPanel" UpdateMode="Conditional" runat="server"> <Triggers> <asp:AsyncPostBackTrigger ControlID="hidCurrentFileId" EventName="ValueChanged" /> </Triggers> <ContentTemplate>   <asp:Label ID="Label1" runat="server" CssClass="QuickEditText" ToolTip="Click to Edit"></asp:Label> <asp:TextBox ID="TextBox1" runat="server" CssClass="QuickEditTextBox" Width="93px"></asp:TextBox> </ContentTemplate></asp:UpdatePanel>

Here's the Code behind for the control

PartialClass QuickEditLabelInherits System.Web.UI.UserControlPrivate myTextAs String Public Property Text()Get Return myTextEnd Get Set(ByVal value) myText = valueEnd Set End Property Protected Sub Page_Load(ByVal senderAs Object,ByVal eAs System.EventArgs)Handles Me.LoadIf Not IsPostBackThen Me.Text ="33"Else Me.Text =Me.TextBox1.TextEnd If Me.TextBox1.Attributes.Add("onchange",Me.hidCurrentFileId.ClientID +"updateNumber(getElementById('" + Me.TextBox1.ClientID + "').value)") Me.Label1.Attributes.Add("onclick", "QuickEditSwap(getElementById('" + Me.TextBox1.ClientID + "'), getElementById('" + Me.Label1.ClientID + "'))")End Sub Protected Sub Page_PreRender(ByVal senderAs Object,ByVal eAs System.EventArgs)Handles Me.PreRenderMe.Label1.Text =Me.TextMe.TextBox1.Text =Me.TextEnd SubEnd Class

Here's the css i'm using for the control

 .QuickEditText {font-family: Verdana;} .QuickEditText:hover {text-decoration: underline; font-family: Verdana; cursor: pointer} .QuickEditTextBox {display: none; font-family:Verdana;}

Thanks in advance for any suggestions,

This is happening because of the default setting of the UpdatePanel's RenderMode property - which will render its contents into a <div> the first time. Try changing it to "Inline" so that it will instead render a <span> element.

Lines and Arrows with Ajax

Hi,

I am trying to create a CASE tool(UML diagrams) on Web using ASP.NET 2.0 andAjax(Atlas). The problem is that I do not know how to create lines and arrows (links between elements).


Is it posible?

Please, help.

JavaScript is very limited to images. SVG and Canvas is what you would have to look into.

Eric

Link Button as trigger not firing

So I have a link button that is created here...

 LinkButton hide =new LinkButton(); hide.Text ="(hide)"; hide.Click +=new EventHandler(this.hide_Click); hide.ID ="hide" + deviceID;

which is later added to a table cell which is added to a table row which is added to a table. This table is what my function returns (the functions basically builds the table)

From where the function is called I have this code to create a trigger using the linkbutton hide, then add that trigger to the update panel that i am putting the newley created table in...

 AsyncPostBackTrigger trig =new AsyncPostBackTrigger(); ((UpdatePanel)tempTable.Parent.Parent).ContentTemplateContainer.Controls.Add(childTable); trig.ControlID = childTable.Rows[0].Cells[1].Controls[1].UniqueID; trig.EventName ="Click"; ((UpdatePanel)childTable.Parent.Parent).Triggers.Add(trig);

I have tried making the controlID both the unique ID and just the ID and neither work. I know that my just for testing my hide_click function is simple...

private void hide_Click(object sender, EventArgs e) { txtOutput.Text ="IT WORKED!"; }

I know the hide_Click function works because i attached it to other buttons in other tables and it executes fine.

Does anyone know if I am doing something wrong because I cannot seem to figure this out.

Thanks

Hi,

what issue are you experiencing? A full postback instead of an async postback? Or the "IT WORKED!" text isn't displayed? In this case, did you put the Label inside an UpdatePanel?


There is no postback at all. The txtOuput is inside an update panel. It works fine when triggered from other buttons that were added to my page the same way I am adding my link button, but something is acting up. Im not sure if there is a problem with where I am adding the trigger so I am going to try defining the trigger at the same place in code as where I am defining the link button to see if that helps, but i doubt that will change anything.


Ok this is really starting to mess with my head. I have noticed now that when i click on my button, the textbox txtOutput refreshes, but still displays the text that was already there, instead of getting the text from the hide_Click function. This is weird though because when I point other buttons to my hide_Click function, they fire it perfectly and the text box updates. I am confussed


Hi,

Please refer to this:

http://ajax.asp.net/docs/mref/T_System_Web_UI_AsyncPostBackTrigger.aspx

Programmatically adding AsyncPostBackTrigger controls is not supported. Use the RegisterAsyncPostBackControl(Control) method of the ScriptManager control to programmatically register a postback control, and then call the Update() method of the UpdatePanel when the control posts back.

Please try as the above documentation described. If still fails, please post a self-sufficient repro.


great thanks, ill take a look. I was all excited because I was able to programatically add asyncpostback trigers to some update panels, I did this at the time the panels were being created and it worked fine, I guess there are some situations where it just doesnt work though.


so it turns out the trigger is working fine, the only problem is that my hide_Click event isnt being fired. I have had this problem before where having certain settings enabled for different controls cause the controls .click event not to work properly, now its just a matter of finding out what is causing this problem

link button inside update panel causes post back

I have a linkbutton inside the update panel. I registered it with AsyncPostBackTrigger, but when I click that link button, the whole page is refreshed instead of that update panel, what could I have gone wrong?

Check the EnablePartialRendering="true" of ScriptManager is et or not ?

Also check UpdateMode="Conditional" of UpdatePanel is set or not ?

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.

Link Click refresh effect?

I got a master page and 2 content page.

the menu links are on the left content page.

How can i get refresh effect on the right content page when i click on the links on the left page?

http://code.google.com/webtoolkit/documentation/examples/kitchensink/demo.htmlHi,

one approach is to use theUpdatePaneltogether with theMultiViewcontrol.
Thanks very much,i got it.
sorry, can i get that kind of effect just click a link on the page without MultView?

eg. i put a link on the left content page. the right content page will refresh when i click the link?

Hi Joytony,

When you click the link, do you want to display a totally new page?? could you post the code you use for the links?

Greetings,

Dennis


Thanks Dennis,

This is the demo i did.

1 master page contain 2 links on it.
while i have 2 content page

~/Default2.aspx
~/Default3.aspx
How can i get the refresh effect in this model?
<%@. Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs" Inherits="MasterPage" %>"-//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">Untitled Page"server"> "form1" runat="server"> "scriptmanager1" EnablePartialRendering="true" runat="Server" /> "up1" runat="server">

"HyperLink1" runat="server" NavigateUrl="~/Default2.aspx">HyperLink "HyperLink2" runat="server" NavigateUrl="~/Default3.aspx">HyperLink

"ContentPlaceHolder1" runat="server">

"Progress" runat="server"> Loading...

sorry, put the code again.
<form id="form1" runat="server"> <atlas:ScriptManager ID="scriptmanager1" EnablePartialRendering="true" runat="Server" /> <atlas:UpdatePanel ID="up1" runat="server"> <ContentTemplate> <div> <asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="~/Default2.aspx">HyperLink</asp:HyperLink> <asp:HyperLink ID="HyperLink2" runat="server" NavigateUrl="~/Default3.aspx">HyperLink</asp:HyperLink> <asp:LinkButton ID="LinkButton1" runat="server">LinkButton</asp:LinkButton> <asp:LinkButton ID="LinkButton2" runat="server">LinkButton</asp:LinkButton> </div> <div> <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server"> </asp:ContentPlaceHolder> </div> </ContentTemplate> </atlas:UpdatePanel> <atlas:UpdateProgress ID="Progress" runat="server"> <ProgressTemplate> Loading... </ProgressTemplate> </atlas:UpdateProgress> </form>

Hi JoyTony,

I don't think that its possible to open a new page in another frame without a full postback. (If this is want you want to achieve). I think that Atlas is useful when you want parts of a webpage to be updated not whole pages. I think that the suggestion above with the multiview is the only option. Is there a reason that you don't want to use multiview??

Greetings,

Dennis


Hi Again,

What is the reason that you put your buttons in the update panel? These controls shoudn't be updated right?

Regards


Hmm, it seems you're kinda misusing the concept., although I do see what you're trying to do i think. If I'm not mistaken you're trying to only get the non master portion to refresh, similar to what one would achieve using frames? If so, other than the fact that it's probably not going to work, your pages will not be picked up by search engines, which is really bad unless its an intranet site.

It would be real nice if ATLAS did solve the problem of same masterpage markup being sent back with every page though, but i guess with a well designed site that should be very minimal.

Nick


Thanks Dennis andnicksh.

The reason why i don't want to use multiple view is i've done many pages there.

I just leave it there at the moment untill we really want to change. Thanks.

Link inside a draghandles template

Is it possible to access a link or a textbox inside a draghandle's template?

I want all the controls inside the draghandle to be dragable and also that users could click on these controls inside the draghandle

talking about ReorderList's DragHandle..

I"m trying to do a similar thing. Originally, I wanted to be able to drag any portion of a ReorderItem to a different position. The problem I ran into is that if you don't declare a position for the DragHandle, you can drag from any place on the ReorderItem BUT this means you cannot click on any controls that are contained in the ReorderItem, making them all useless. The control thinks that if you click ANYWHERE, you're trying to drag it, so the controls can never be used.

So, to remedy this problem, I thought to do exactly what you're doing. I added a <DragHandle> to the left side which contains a Label; this Label was to hold the sequence number of the ReorderItems (so the first item would have a 1, the second would contain a 2, etc), but like you I cannot access this control from the code behind when the Reorder event fires.


your problem seems diferent than mine. I don't have any problems accesing controls in the code behind. I'm trying to figure out how to make some parts of the draghandle dragable and some of them "clickable". I guess i need to construct some <div> element consisting of several other <div> elements and put a draghandle inside one of them. But here is another problem: you cannot place the draghandle anywhere you like, just four possitions. So i cannot put it inside a particular <div> element

I guess i need to think another way to do it

link usage by ajax framework

HI, I am new using ajax... so..I created a small project with a few controls inside a page.I was doing well every think fine.So I started a web test project to see the impact of using ajax inside my page (link usage)...and what I see was a use of a "library" off size 250Kb ...Is this correct I doing something wrong ?

The controls that I was testing was part off the toolkit

Hi,

According to my understanding, you noticed a .js file with size of 250 KB was downloaded.

This is the correct behavior. Actually, AJAX is implemented with javascript, which will be responsible for sending request asynchronously, update contents on the web form. And there are also a lot auxiliary methods and objects.

So, it's normal to see this.

Just pay attention to changing the debug mode to false in web.config before you are going to deploy your application.


I would like to know if this .js will be downloaded at each post in the page? For navigation between different pages that use Ajax technology .js will be downloaded several times? What I expected is that .js was to be downloaded only once. But my tests don't show this! Am I correct? Or I am loosing something Thank you Very Much

You need to set debug to false in web.config.

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 and AJAX

<asp:UpdatePanelID="menuUpdate"runat="server">

<ContentTemplate>

<divid="menuRow"runat="server"class="menuRow">

</div>

</ContentTemplate>

</asp:UpdatePanel>

The above is in my ASPX file. I am adding linkButtons to MenuRow during the PAGE_LOAD on the server. The resulting HTML is as follows:

<div id="ctl00_menuUpdate">
<div id="ctl00_menuRow" class="menuRow">
<a class="menuRow1" ID="cell189" runat="server" href="http://links.10026.com/?link=javascript:__doPostBack('ctl00$ctl05','')">Home</a></div>
</div>

I dont want this to refresh the page. I have a Click event for that linkButton and it is executing, but it is also sending the whole page back to the server, not just the updatePanel.

Any thoughts?

I was assigning the ID via Attributes.Add('ID','someValue') and I needed to set the ID via this.ID.

Works as advertised.

Thanks.

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 inside accordionPane header

Hello.

I have an accordion with some panes. In panes header I have a text and a linkbutton. I want to open a pane when user clicks on text, but I don't want to open (or close) the pane when user clicks on linkbutton. When user clicks linkbutton the pane must not move.

Anyone knows how can I do it?

Thanks!!! and sorry for my english (greetings from Spain! :D)


I would also like to know. Looking at the source code I cant seem to find anything short of re-writing in javascript a number of functions.

Rather disappointed with the level of support for these kind of things this control has.


Please someone can help us? :-(


Hi,

The reason and solution has been discussed in this post: http://forums.asp.net/p/1133424/1809338.aspx

Please try it.


I searched before but i didn't find it.

THAT WORKS!!!


THANK YOU A LOT!Cool

LinkButton inside a repeater as a trigger

 I have been searching all over for an answer but have yet to find anything. 

I have a repeater that I use to display a letter paging system. It looks something like this

<asp:Repeater ID="rpt_Letters" runat="server"> <ItemTemplate> <asp:LinkButton ID="lbtn_Letter" CausesValidation="false" CommandName="Filter" CommandArgument='<%# Eval("Letter") %>' runat="server" style="padding-left:7px; padding-top: 10px;" ToolTip='<%# Eval("Letter") %>'><%# Eval("Letter") %></asp:LinkButton> </ItemTemplate> </asp:Repeater>

Once a letter is clicked I want to update the information in a GridView.

I have the GridView in an update panel, but I can't find away to set my Letter Paging as a trigger.

Thank You!


.csharpcode, .csharpcode pre{font-size: small;color: black;font-family: Consolas, "Courier New", Courier, Monospace;background-color: #ffffff;/*white-space: pre;*/}.csharpcode pre { margin: 0em; }.csharpcode .rem { color: #008000; }.csharpcode .kwrd { color: #0000ff; }.csharpcode .str { color: #006080; }.csharpcode .op { color: #0000c0; }.csharpcode .preproc { color: #cc6633; }.csharpcode .asp { background-color: #ffff00; }.csharpcode .html { color: #800000; }.csharpcode .attr { color: #ff0000; }.csharpcode .alt {background-color: #f4f4f4;width: 100%;margin: 0em;}.csharpcode .lnum { color: #606060; }
Add your repeater control to an UpdatePanel as follows:<asp:UpdatePanelID="PagingPanel"UpdateMode="Conditional"runat="server"><ContentTemplate><asp:RepeaterId="">...</asp:Repeater>and put your gridview control in another UpdatePanel like this:<asp:UpdatePanelID="OrderDetailsPanel"UpdateMode="Always"runat="server"><ContentTemplate><asp:gridview/>And then add handler for OnCommand event of the linkbutton (lbtn_Letter) where you can filter rows like this:protected void Letter_OnCommand(object sender, CommandEventArguments e) { SqlDataSource2.SelectParameters["OrderID"].DefaultValue = e.CommandArgument ;SqlDataSource2.DataBind();}where SqlDataSource2 is bound to your GridView control.That's it.

Thanks!

Linkbutton inside update panel not working and causing exception

I page that contains an update panel. this page has a linkbutton that redirects to a new page and opens that page in a a new window(the page redirected to displays a picture). This linkbutton has been working all along with after adding this line of code in the pageload event.

ScriptManager.GetCurrent(Page).RegisterPostBackControl(LinkButton23)

suddenly, the linkbutton can nolonger redirect to the page when clicked and iam not aware of anything i did that may have crewed it up. I now get the following error message when i click it.

sys.webforms.webrequestmanagerParsererrorException: The message recieved from the server could not be parsed . Common causes for this error are when the response is modified by calls to response.write(), response.filters or server trace is enabled. Details: Error parsing near '<script language="ja'.

Actually i have noticed very strange behaviours by my IDE since i installed windows updates on tuesday, things like button click events not firing.

Any help.

Iam not sure if this extra information may help me get a reply. After some googling, most results are pointing to some thing to do with response.write in an update panel.

And in side the click event of my linkbutton, i have these javascript lines of code

ProtectedSub LinkButton23_Click1(ByVal senderAsObject,ByVal eAs System.EventArgs)

Dim myScriptAsString ="<script language=""javascript"">window.open('human Resources/viewer.aspx?id=" + employeenumber.SelectedValue +"') </" +"script>"

Response.Write(myScript)

EndSub

Iam not sure if this could be the cause of the problem but just in case.


<%@.PageLanguage="VB"AutoEventWireup="false" %>

I just changedAutoEventWireup from ="false" to="true" and every thing is back to normal, makes look stupid after wasting loosing over 8 hours. One more gotcha learnt though.

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 plays "click sound" (postbacks the whole page?)

Hi,

This is my first post here at the ASP.NET forums and I'm not sure if I'm in the correct category, so please correct me if I'm wrong.

My question concerns the LinkButton when used with AJAX .NET 1.0 RC1. I have a GridView inside a UpdatePanel. Inside that GridView there are various controls, some of them LinkButtons. When I click, for example, a ImageButton the UpdatePanel refreshes without making any "click sound" (the sound that Internet Explorer plays when a new page is requested). However, if I click a LinkButton the click sound is played. Why is this? If I replace all LinkButtons with normal Buttons or ImageButtons no click sound is heard, so the issue seems related to the LinkButton only. Is this behavior by design, or am I doing something wrong? Is the whole page postbacked when I click a LinkButton even if it resides in an UpdatePanel?

Thanks in advance!

If you place a asp:LinkButton in a asp:UpdatePanel and specify asynchronous post back, there should not be the whole page postback.Try to google "Click Sound" of the asp:LinkButton for some ideas.Maybe this is caused by the designers, which there is sound when clicking a asp:LinkButton.

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.

LinkButton Trigger inside a repeater

 I have been searching all over for an answer but have yet to find anything. 

I have a repeater that I use to display a letter paging system. It looks something like this

<asp:Repeater ID="rpt_Letters" runat="server"> <ItemTemplate> <asp:LinkButton ID="lbtn_Letter" CausesValidation="false" CommandName="Filter" CommandArgument='<%# Eval("Letter") %>' runat="server" style="padding-left:7px; padding-top: 10px;" ToolTip='<%# Eval("Letter") %>'><%# Eval("Letter") %></asp:LinkButton> </ItemTemplate> </asp:Repeater>

Once a letter is clicked I want to update the information in a GridView.

I have the GridView in an update panel, but I can't find away to set my Letter Paging as a trigger.


Hi,

an approach could be wrapping the repeater with an UpdatePanel with UpdateMode="Conditional" and ChildrenAsTriggers="false". This won't make the panel update when a LinkButton is clicked, but will trigger an asynchronous postback where you can update the panel that contains the GridView. Check this basic example:

<%@. Page Language="C#" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><script runat="server"> protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { repTriggers.DataSource = new int[3] { 0, 1, 2 }; repTriggers.DataBind(); } } protected void repTriggers_ItemCommand(object sender, RepeaterCommandEventArgs e) { if (e.CommandName == "trigger") { LinkButton btn = e.CommandSource as LinkButton; if (btn != null) { lblUpdate.Text = "Update triggered by " + btn.ID + e.Item.ItemIndex.ToString(); } UpdatePanel2.Update(); } }</script><html xmlns="http://www.w3.org/1999/xhtml" ><head runat="server"> <title>Untitled Page</title></head><body> <form id="form1" runat="server"> <asp:ScriptManager ID="TheScriptManager" runat="server"></asp:ScriptManager> <asp:UpdatePanel ID="UpdatePanel1" runat="server" ChildrenAsTriggers="false" UpdateMode="conditional"> <ContentTemplate> <asp:Repeater ID="repTriggers" runat="server" OnItemCommand="repTriggers_ItemCommand"> <ItemTemplate> <asp:LinkButton ID="lnkTrigger" runat="server" Text="Trigger" CommandName="trigger"></asp:LinkButton> </ItemTemplate> </asp:Repeater> </ContentTemplate> </asp:UpdatePanel> <asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="conditional"> <ContentTemplate> <asp:Label ID="lblUpdate" runat="server"></asp:Label> </ContentTemplate> </asp:UpdatePanel> </form></body></html>

Good suggestion, Garbin, but I think I have an even easier way. You can simply add your Repeater as a trigger for your UpdatePanel. Here's my version, with comments indicating where it differs from Garbin's:

<%@. Page Language="C#" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><script runat="server"> protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { repTriggers.DataSource = new int[3] { 0, 1, 2 }; repTriggers.DataBind(); } } protected void repTriggers_ItemCommand(object sender, RepeaterCommandEventArgs e) { if (e.CommandName == "trigger") { LinkButton btn = e.CommandSource as LinkButton; if (btn != null) { lblUpdate.Text = "Update triggered by " + btn.ID + e.Item.ItemIndex.ToString(); } // [Steve] removed UpdatePanel2.Update() } }</script><html xmlns="http://www.w3.org/1999/xhtml" ><head id="Head1" runat="server"> <title>Untitled Page</title></head><body> <form id="form1" runat="server"> <asp:ScriptManager ID="TheScriptManager" runat="server"></asp:ScriptManager><%-- [Steve] removed UpdatePanel1 --%> <asp:Repeater ID="repTriggers" runat="server" OnItemCommand="repTriggers_ItemCommand"> <ItemTemplate> <asp:LinkButton ID="lnkTrigger" runat="server" Text="Trigger" CommandName="trigger"></asp:LinkButton> </ItemTemplate> </asp:Repeater> <asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="conditional"><%-- [Steve] added repTriggers as an AsyncPostBackTrigger --%> <Triggers> <asp:AsyncPostBackTrigger ControlID="repTriggers" /> </Triggers> <ContentTemplate> <asp:Label ID="lblUpdate" runat="server"></asp:Label> </ContentTemplate> </asp:UpdatePanel> </form></body></html>

Hi,

yes, definitely :)


Thank you!

That was too easy! I can't believe I never tried that.Embarrassed

LinkButton/DataGrid/HoverMenu Issue - Linkbutton not passing values?

Hello all,
I have a unique situation here, that I have been stumped on for 3 days now. I have a nested master/detail form as seen below, and within the 2nd grid I have an AJAX hovermenu, for some reason I am not able to collect the values of the form when the user wants to insert the values. I am able to capture the linkbutton event in the code behind but, when it gets to the assigning of the textbox value for entry into the DB it is comes up with a reference not set to the instance of an object. The first set of code is the asp.net page the second set is the code behind, any pointers on this would be extremely helpful, and I would owe you like lunch or something :) Thanks again for all of your help.

ASP.Net Code

1<asp:UpdatePanel ID="up0" runat="server" Visible="true">2 <ContentTemplate>3 <asp:GridView4 ID="GridView1"5 runat="server"6 Width="656px"7 CellPadding="4"8 DataSourceID="SqlDataSource1"9 ForeColor="#333333"10 OnRowDataBound="bindMarketControl"11 AutoGenerateColumns="False"12 GridLines="None"13 >14 <Columns>15 <asp:TemplateField>16 <ItemTemplate>17 <h2><%# Eval("MarketName")%></h2>18 <table width="100%">19 <tr>20 <td width="200px">Team Name</td>21 <td width="200px">Head Count</td>22 <td width="200px">Orders</td>23 <td width="200px">Revenue</td>24 </tr>25 </table>26 <asp:UpdatePanel ID="up1" runat="server">27 <ContentTemplate>28 <asp:GridView29 ID="TeamDetail"30 DataSourceID="GetTeamDetailFormView"31 AutoGenerateColumns="False"32 ShowHeader="False"33 GridLines="None"34 runat="server">35 <Columns>36 <asp:TemplateField>3738 <ItemTemplate>39 <asp:Panel CssClass="popupMenu" ID="PopupMenu" runat="server">40 <div style="border:1px outset white;padding:2px;">41 <div><asp:LinkButton42 ID="LinkButton1"43 runat="server"44 CommandName="Edit"45 Text="Edit"46 /></div>47 <div><asp:LinkButton48 ID="LinkButton2"49 runat="server"50 CommandName="Delete"51 Text="Delete" /></div>52 </div>53 </asp:Panel>54 <asp:Panel ID="Panel9" runat="server">55 <table width="100%">56 <tr>57 <td width="195px">58 <asp:Label59 Font-Bold="true"60 ID="Label0"61 runat="server"62 Text='<%# Eval("TeamName")%>' />63 </td>64 <td width="200px">65 <asp:Label66 ID="Label1"67 runat="server"68 Text='<%# Eval("HeadCount")%>' />69 </td>70 <td width="200px">71 <asp:Label72 ID="Label2"73 runat="server"74 Text='<%# Eval("Orders")%>' />75 </td>76 <td width="200px">77 <asp:Label78 ID="Label3"79 runat="server"80 Text='<%# Eval("Revenue")%>' />81 </td>82 </tr>83 </table>84 </asp:Panel>85 <cc1:HoverMenuExtender ID="hme2"86 HoverCssClass="popupHover"87 PopupControlID="PopupMenu"88 PopupPosition="Left"89 TargetControlID="Panel9"90 PopDelay="25"91 runat="server" />92 </ItemTemplate>93 <EditItemTemplate>94 <asp:Panel ID="Panel9" runat="server" Width="100%">95 <table width="100%">96 <tr>97 <td width="200px">98 <asp:TextBox99 ID="TextBox00"100 runat="server"101 Text='<%# Bind("TeamId")%>'102 Visible="false"103 EnableViewState="true"104 />105 <asp:TextBox106 ReadOnly="true"107 Font-Bold="true"108 ID="TextBox0"109 runat="server"110 Text='<%# Bind("TeamName")%>'111 EnableViewState="true" />112 </td>113 <td width="200px">114 <asp:TextBox115 ID="TextBox1"116 runat="server"117 Text='<%# Bind("HeadCount")%>'118 EnableViewState="true" />119 </td>120 <td width="200px">121 <asp:TextBox122 ID="TextBox2"123 runat="server"124 Text='<%# Bind("Orders")%>'125 EnableViewState="true"126 />127 </td>128 <td width="200px">129 <asp:TextBox130 ID="TextBox3"131 runat="server"132 Text='<%# Bind("Revenue")%>'133 EnableViewState="true" />134 </td>135 </tr>136 </table>137 </asp:Panel>138 <cc1:HoverMenuExtender139 ID="hme1"140 TargetControlID="Panel9"141 PopupControlID="PopupMenu"142 HoverCssClass="popupHover"143 PopupPosition="Right"144 runat="server">145 </cc1:HoverMenuExtender>146 <asp:Panel ID="PopupMenu" runat="server" CssClass="popupMenu">147 <div style="border:1px outset white">148 <div>149 <asp:LinkButton150 ID="lbtnInsertUpdate"151 runat="server"152 CausesValidation="True"153 CommandName="Insert"154 Text="Insert"155 OnClick="lbtnInsertUpdate_Click"156 />157 </div>158 <div>159 <asp:LinkButton160 ID="LinkButton2"161 runat="server"162 CausesValidation="False"163 CommandName="Cancel"164 Text="Cancel" /></div>165 </div>166 </asp:Panel>167 </EditItemTemplate>168 </asp:TemplateField>169 </Columns>170 </asp:GridView>171 </ContentTemplate>172 </asp:UpdatePanel>173 <asp:SqlDataSource174 ID="GetTeamDetailFormView"175 runat="server"176 ConnectionString="<%$ ConnectionStrings:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX%>"177 SelectCommand="sp_GetTeamDetails"178 SelectCommandType="StoredProcedure"179 InsertCommand="sp_InsertDataInfo"180 InsertCommandType="StoredProcedure">181 <SelectParameters>182 <asp:Parameter Name="MarketID" />183 <asp:ControlParameter184 ControlID="ddlVPInfo"185 DefaultValue=""186 Name="vpid"187 PropertyName="SelectedValue"188 Type="Int32" />189 </SelectParameters>190 <InsertParameters>191 <asp:Parameter Name="TeamID" />192 <asp:Parameter Name="HeadCount" />193 <asp:Parameter Name="Orders" />194 <asp:Parameter Name="Revenue" />195 <asp:ControlParameter196 ControlID="tbEntryDat"197 Name="DataDate"198 PropertyName="Text"199 Type="String" />200 </InsertParameters>201 </asp:SqlDataSource>202 <hr />203 </ItemTemplate>204 </asp:TemplateField>205 </Columns>206 </asp:GridView>207208 <asp:SqlDataSource209 ID="SqlDataSource1"210 runat="server"211 ConnectionString="<%$ ConnectionStrings:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX%>"212 SelectCommand="sp_GetMarketCats"213 SelectCommandType="StoredProcedure">214 <SelectParameters>215 <asp:ControlParameter216 ControlID="ddlVPInfo"217 DefaultValue=""218 Name="vpid"219 PropertyName="SelectedValue"220 Type="Int32" />221 </SelectParameters>222 </asp:SqlDataSource>223224 </ContentTemplate>225 <Triggers>226 <asp:AsyncPostBackTrigger227 ControlID="btnDisplayEntry"228 EventName="Click" />229 </Triggers>230 </asp:UpdatePanel>

The Code Behind

1Protected Sub lbtnInsertUpdate_Click(ByVal senderAs Object,ByVal eAs EventArgs)2Dim TeamInfoDBConnAs New SqlConnection(ConfigurationManager.ConnectionStrings("XXXXXXXXXXXXXXXXX").ConnectionString)3Dim sqlStringAs String ="sp_InsertDataInfo"4Dim sqlCmdAs New SqlCommand(sqlString, TeamInfoDBConn)5 sqlCmd.CommandType = CommandType.StoredProcedure67'Dim NewText As String =8 'Dim val1 As TextBox = CType(e.Item.FindControl("TextBox3"), TextBox)9 'MsgBox(val1.Text)101112 sqlCmd.Parameters.AddWithValue("@dotnet.itags.org.TeamID", TextBox00.Text)13 sqlCmd.Parameters.AddWithValue("@dotnet.itags.org.HeadCount", TextBox1.Text)14 sqlCmd.Parameters.AddWithValue("@dotnet.itags.org.Orders", TextBox2.Text)15 sqlCmd.Parameters.AddWithValue("@dotnet.itags.org.Revenue", TextBox3.Text)16 sqlCmd.Parameters.AddWithValue("@dotnet.itags.org.DataDate", tbEntryDate.Text)1718 TeamInfoDBConn.Open()19 sqlCmd.ExecuteNonQuery()20 TeamInfoDBConn.Close()21 sqlCmd =Nothing22 End Sub

Bump...Still looking for anyone that might have some idea about this one?? thank-you!

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