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)