How to pass parameter to Eval() in Link Button Control?

Michael picture Michael · Jan 28, 2012 · Viewed 16.2k times · Source

ASP Declaration:

 <asp:LinkButton ID="LinkButton1" runat="server" Text="edit item" onclick="'AddItem.aspx?catid=<%# Eval("CollectionID")%>'"></asp:LinkButton>

I get Error: The server tag is not well formed.

what the problem with LinkButton decloration? Thank you in advance.

Answer

Tim Medora picture Tim Medora · Jan 28, 2012
<asp:LinkButton ID="LinkButton1" runat="server" Text="edit item" onclick='AddItem.aspx?catid=<%# Eval("CollectionID")%>' />

I removed extraneous quotes around the attribute value for OnClick.

However, OnClick expects a delegate, not a URL. Either use a hyperlink or switch to an event handler.

<a href='AddItem.aspx?catid=<%# Eval("CollectionID")%>'>edit item</a>

This article shows how to pass an argument to an event handler from a link button. Instead of using OnClick, you can use OnCommand and set the CommandArgument property.

In Markup

  <asp:LinkButton id="lnkEdit" 
       Text="Edit Item"
       CommandArgument='<%# Eval("CollectionID")%>'
       OnCommand="lnkEdit_Command" 
       runat="server"/>

In Codebehind

protected void lnkEdit_Command( object sender, CommandEventArgs e )
{
    // evaluate e.CommandArgument and do something with it
}

I favor using a URL versus a command event handler whenever possible as it eliminates a comparatively expensive postback.