1. Using CommandSource object
2. Using CommandArgument property
Ok our target is to add an action button within GridView rows & get the RowIndex number from RowCommand Method like below:
Using CommandSource object:
To do that first add a GridView with a LinkButton in a template field like below:
<asp:GridView ID="GridView1" runat="server" Width="800px" AutoGenerateColumns="False" OnRowCommand="GridView1_RowCommand" > <HeaderStyle BackColor="Red" Font-Bold="true" ForeColor="White" /> <RowStyle BackColor="LightGray" /> <AlternatingRowStyle BackColor="LightGray" /> <Columns> <asp:BoundField DataField="Brand Name" HeaderText="Brand Name" /> <asp:BoundField DataField="Category Name" HeaderText="Category Name" /> <asp:BoundField DataField="Product Name" HeaderText="Product Name" /> <asp:TemplateField HeaderText="Submit" ItemStyle-HorizontalAlign="Center"> <ItemTemplate> <asp:LinkButton ID="lnkSubmit" runat="server" CommandName="Submit" Text="Action" ></asp:LinkButton> </ItemTemplate> <EditItemTemplate> </EditItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> <hr /> <asp:Label runat="server" ID="lblRowIndex" Font-Bold="True" Font-Size="Larger"></asp:Label>
Now go to the design mode. Right click on GridView to get property window. From event list select RowCommand event. Double click to write the method code like below:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e) { if (e.CommandName.Equals("Submit")) { GridViewRow oItem = (GridViewRow)((LinkButton)e.CommandSource).NamingContainer; int RowIndex = oItem.RowIndex; lblRowIndex.Text = "Row Index = "+RowIndex.ToString(); } }Now run the page & click on any one of the Action linkbutton. The label shows the RowIndex number of your clicked Action button.