Handling events of Control's inside ASP.NET ListView

A user recently asked me on the forums that he has a LinkButton kept inside a ListView that displayed the ProductNames. When a user clicks on the LinkButton, he should get the ProductID in codebehind to retrieve other details. Here's a quick and dirty way of how to do so by handling the OnItemCommand event of the ListView control

<asp:ListView ID="lvProducts" runat="server" DataSourceID="SqlDataSource1"

OnItemCommand="lvProducts_ItemCommand" ItemPlaceholderID="PlaceHolder1">




        runat="server" />



    <asp:LinkButton ID="LinkButton1" CommandArgument='<%# Eval("ProductID") %>'

    Text='<%# Eval("ProductName") %>' CommandName="View Details"

    runat="server"></asp:LinkButton><br />



<asp:SqlDataSource ID="SqlDataSource1" runat="server"

    ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"

    SelectCommand="SELECT [ProductID], [ProductName], [UnitPrice] FROM [Products]">



protected void lvProducts_ItemCommand(object sender, ListViewCommandEventArgs e)


    if (e.CommandName == "View Details")


        int productId = (int)e.CommandArgument;




    Protected Sub lvProducts_ItemCommand(ByVal sender As Object, ByVal e As ListViewCommandEventArgs)

        If e.CommandName = "View Details" Then

            Dim productId As Integer = CInt(e.CommandArgument)

        End If

    End Sub

Will you give this article a +1 ? Thanks in advance

About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

1 comment:

infront said...

Many thanks - this is really clear and allows me to get out of a hole I had dug for myself!