0
votes

I'm a noob and trying to make a demo with commandname and commandargument. please show me how to create an edit button with asp:LinkButton

    <table>
        <asp:Repeater ID="Repeater1" runat="server" >
            <HeaderTemplate>
                <tr>
                    <th> FirstName </th>
                    <th> LastName </th>
                </tr>
            </HeaderTemplate>
            <ItemTemplate>
                <tr>
                    <td> <%# Eval("FirstName")%></td>
                    <td> <%# Eval("LastName")%></td>
                    <asp:LinkButton ID="EditButton"  runat="server" Text="Edit" CommandName="EditName" CommandArgument="EditArgument" ></asp:LinkButton>
                </tr>
            </ItemTemplate>
        </asp:Repeater>
    </table>
2

2 Answers

1
votes

You need to create a click event handler for you link button, like this:

Markup:

<table>
    <asp:Repeater ID="Repeater1" runat="server" >
        <HeaderTemplate>
            <tr>
                <th> FirstName </th>
                <th> LastName </th>
            </tr>
        </HeaderTemplate>
        <ItemTemplate>
            <tr>
                <td> <%# Eval("FirstName")%></td>
                <td> <%# Eval("LastName")%></td>
                <asp:LinkButton ID="EditButton"  runat="server" Text="Edit" 
                                CommandName="EditName" 
                                CommandArgument="EditArgument" 
                                OnClick="OnClickHandler" >
                </asp:LinkButton>
            </tr>
        </ItemTemplate>
    </asp:Repeater>
</table>

Code-behind:

protected void OnClickHandler(object sender, EventArgs e)
{
    var theLinkButton = sender as LinkButton;

    // The as operator returns null if the cast fails
    // Check to see if link button exists before we try to use it
    if(theLinkButton != null)
    {
        // Check for CommandName from markup
        if(theLinkButton.CommandName = "EditName")
        {
            // Do logic here to edit name
        }

        // Other CommandName values could be handled here
    }
}

Note: If you had another button, say Delete for example, then you could have its OnClick value point to the same method OnClickHandler and then pass a different CommandName value to have it do different, thus one handler for multiple actions.

0
votes

Just add event handler for your repeater itemcommand event

protected void Repeater_ItemCommand(object sender, RepeaterCommandEventArgs e) 
{
  if (e.CommandName == "EditName")
  {
    //TODO something
  }
}