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

About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

1 comment:

Unknown said...

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