jQuery and ASP.NET

March 24, 2009

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




'Like' us on our FaceBook page if you find this blog useful. Thanks!


Did you like this post?
kick it on DotNetKicks.com Save on Delicious
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP 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 has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

comments

1 Response to "Handling events of Control's inside ASP.NET ListView"
  1. infront said...
    July 27, 2010 1:25 PM

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

 

Copyright © 2009-2011 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions