ASP.Net Repeater: Get Item, ItemIndex, CommandName and CommandArgument on Click Events
 
Author:
Filed Under: ASP.Net  |  Repeater
Published Date: Sep 13, 2011
Views: 3069
 

Abstract: Here Mudassar Ahmed Khan has explained how to get the RepeaterItem reference, RepeaterItem ItemIndex, CommandName and CommandArgument when Button, LinkButton or ImageButton is clicked.

Comments:  1

 

In this article I will explain how to get the Repeater Item, Repeater Item Index, CommandName and CommandArgument when a Button, ImageButton or LinkButton is clicked.
 
ASP.Net Repeater
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
    <asp:Label ID="Label2" runat="server" Text='<%# Eval("ContactName") %>'></asp:Label>
    <asp:Button ID="Button1" runat="server" Text="Button" OnClick = "Button_Click" CommandArgument = '<%# Eval("ContactID") %>' />
</ItemTemplate>
</asp:Repeater>

Above you might have noticed that the ASP.Net Repeater control has a Button which when clicked raises a button click event.
 
Get Repeater Item and Repeater Item Index when Button is clicked
Below code explains how to get the ASP.Net Repeater Item, ItemIndex, Button reference and its CommandArgument.
C#
protected void Button_Click(object sender, EventArgs e)
{
    //Get the reference of the clicked button.
    Button button = (sender as Button);
 
    //Get the command argument
    string commandArgument = button.CommandArgument;
 
    //Get the Repeater Item reference
    RepeaterItem item = button.NamingContainer as RepeaterItem;
 
    //Get the repeater item index
    int index = item.ItemIndex;
}
 
VB.Net
Protected Sub Button_Click(ByVal sender As Object, ByVal e As EventArgs)
   'Get the reference of the clicked button.
   Dim button As Button = CType(sender, Button)
  
   'Get the command argument
   Dim commandArgument As String = button.CommandArgument
  
   'Get the Repeater Item reference
   Dim item As RepeaterItem = CType(button.NamingContainer, RepeaterItem)
  
   'Get the repeater item index
   Dim index As Integer = item.ItemIndex
End Sub
 
Same way you can do it for LinkButton and ImageButton. Just by typecasting sender  
LinkButton
C#
(sender as LinkButton);
VB.Net
CType(sender, LinkButton)
 
ImageButton
C#
(sender as ImageButton);
VB.Net
CType(sender, ImageButton)
 








Related Articles



Comments



Add comments

You can add your comment about this article using the form below. Make sure you provide a valid email address
else you won't be notified when the author replies to your comment

Please note that all comments are moderated and will be deleted if they are
  • Not relavant to the article
  • Spam
  • Advertising campaigns or links to other sites
  • Abusive content.
Please do not post code, scripts or snippets.

Name*: Required
Email*: Required
Comment*: Required
Security code*: CaptchaInvalid Security Code
  Submit