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">


 <LayoutTemplate>


        <asp:Placeholder


        id="PlaceHolder1"


        runat="server" />


    </LayoutTemplate>


<ItemTemplate>


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


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


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


</ItemTemplate>


</asp:ListView>


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


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


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


</asp:SqlDataSource>





C#


protected void lvProducts_ItemCommand(object sender, ListViewCommandEventArgs e)


{


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


    {


        int productId = (int)e.CommandArgument;


    }


}




VB.NET


    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!