Handle the button click event from an ASP.NET ListView control

Here is how you can handle the event of a button from within an ASP.NET ListView control.

Add your button to the ListView Template like you would any other control:

<asp:ListView ItemPlaceholderID="Test" runat="server" ID="ListView1" >
    <ItemTemplate>
        <asp:Button runat="server" Text='<%# Eval("MyProperty") %>' CommandArgument='<%# Eval("MyProperty") %>' /><br />
    </ItemTemplate>
</asp:ListView>

image

And then handle the ListView.ItemCommand event in your code:

image

That is really all there is to it.  The ListView will bubble up the Button’s click event to the ListView_ItemCommand event handler and then you can handle it there.  You can also use the CommandArgument property to send button specific data, such as the particular ID of the row or item that the user clicked the button for.

This call also be used on some of the other databound controls such as the ASP.NET Repeater.

 

Full Example Code:

ListViewButtonExample.aspx:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ListViewButtonExample.aspx.cs" Inherits="ListViewButtonExample" %>
<html>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ListView ItemPlaceholderID="Test" runat="server" ID="ListView1" >
            <LayoutTemplate>
                <asp:Literal runat="server" ID="Test"></asp:Literal>
            </LayoutTemplate>
            <ItemTemplate>
                <asp:Literal runat="server" Text='<%# Eval("MyProperty") %>'></asp:Literal>
                <asp:Button runat="server" Text='<%# Eval("MyProperty") %>' CommandArgument='<%# Eval("MyProperty") %>' /><br />
            </ItemTemplate>
        </asp:ListView>
        <asp:Literal runat="server" ID="Literal1"></asp:Literal>
    </div>
    </form>
</body>
</html>

ListViewButtonExample.aspx.cs:
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using System.Collections;

public class MyObject
{
    public String MyProperty { get; set; }
}
public partial class ListViewButtonExample : System.Web.UI.Page
{
    protected void Page_Init(object sender, EventArgs e)
    {
        ListView1.ItemCommand += new EventHandler<ListViewCommandEventArgs>(ListView1_ItemCommand);
    }

    void ListView1_ItemCommand(object sender, ListViewCommandEventArgs e)
    {
        Literal1.Text = "You clicked the " + (String)e.CommandArgument + " button";
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            List<MyObject> col = new List<MyObject>();
            col.Add(new MyObject { MyProperty = "test 1" });
            col.Add(new MyObject { MyProperty = "test 2" });
            ListView1.DataSource = col;
            ListView1.DataBind();
        }
    }
}

 

Technorati Tags: ,


8 Comments

Comments have been disabled for this content.