How To Get RowIndex of Asp.Net GridView RowCommand Event C# VB.Net

As we know that if we add any Button control or Image Button control or Link Button within the GridView and click to generate postback event then GridView RowCommand Event will fire. But the problem is, from this RowCommand method we did not easily get the Cliclked or Selected GridView Row Index Number. To get the RowIndex of Asp.Net GridView from RowCommand Event we have two options:

1. Using CommandSource object
2. Using CommandArgument property

Add an action button within GridView rows & Get the RowIndex number from RowCommand Method like below:

How To get RowIndex of Asp.Net GridView in the RowCommand Event CSHARP VB.Net

To do the Example First Create 2 Database Tables:

CREATE TABLE [dbo].[Brand](
	[ID] [bigint] NOT NULL,
	[Name] [varchar](max) NOT NULL,
 CONSTRAINT [PK_Brand] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

CREATE TABLE [dbo].[Product](
	[ID] [bigint] NOT NULL,
	[Name] [varchar](max) NULL,
	[Description] [varchar](max) NULL,
	[BrandID] [bigint] NULL,
 CONSTRAINT [PK_Product_2] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

Now Insert Some Data:

INSERT INTO Brand Values(1,'Kohinoor')
INSERT INTO Brand Values(2,'Proctor & Gamble')
INSERT INTO Brand Values(3,'Telenor')
INSERT INTO Brand Values(4,'Unilever')

INSERT INTO PRODUCT VALUES(1,'Lux Beauty Soap','Product of Unilever',4)
INSERT INTO PRODUCT VALUES(2,'Tibbet Pomed','Winter Product',1)
INSERT INTO PRODUCT VALUES(3,'Data SIM','Subscriber Identity Module',3)
INSERT INTO PRODUCT VALUES(4,'Nippon','Color Television',1)

Now modify the Web.Config File to Connect to Database:

<configuration>
  <connectionStrings>
    <add name="DBConnection" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=TESTDB;Trusted_Connection=yes;" providerName="System.Data.SqlClient"/>
    <!--<add name="BONConnection" connectionString="Data Source=XXX.com;Initial Catalog=DBNAME;User Id=UserName;Password=YourPassword;" providerName="System.Data.SqlClient" />-->
  </connectionStrings>
...................
...................

Note: If you use windows authentication then use the first key. Otherwise use second key line. Update server name, Database name, User name, Password as per your settings.

Using CommandSource object:
First add a GridView with a LinkButton in a template field like below:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowCommand="GridView1_RowCommand" HeaderStyle-BackColor="CornflowerBlue" HeaderStyle-Font-Bold="true" HeaderStyle-ForeColor="White" CellPadding="5">
         <Columns>
             <asp:BoundField DataField="Name" HeaderText="Name" />
             <asp:BoundField DataField="Description" HeaderText="Description" />
             <asp:BoundField DataField="Brand" HeaderText="Brand" />

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

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:

C# Code:

    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();
        }
    }

VB.Net Code:

    Protected Sub GridView1_RowCommand(sender As Object, e As GridViewCommandEventArgs)
        If e.CommandName.Equals("Submit") Then
            Dim oItem As GridViewRow = DirectCast(DirectCast(e.CommandSource, LinkButton).NamingContainer, GridViewRow)
            Dim RowIndex As Integer = oItem.RowIndex
            lblRowIndex.Text = "Row Index = " & RowIndex.ToString()
        End If
    End Sub

Now run the page & click on any one of the Action linkbutton. The label shows the RowIndex number of your clicked Action button.

Using CommandArgument property:
To do that first add a GridView with a LinkButton in a template field like below:
C# Code:

        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowCommand="GridView1_RowCommand" HeaderStyle-BackColor="CornflowerBlue" HeaderStyle-Font-Bold="true" HeaderStyle-ForeColor="White" CellPadding="5">
         <Columns>
             <asp:BoundField DataField="Name" HeaderText="Name" />
             <asp:BoundField DataField="Description" HeaderText="Description" />
             <asp:BoundField DataField="Brand" HeaderText="Brand" />

                <asp:TemplateField HeaderText="Submit" ItemStyle-HorizontalAlign="Center"> 
                <ItemTemplate> 
                <asp:LinkButton ID="lnkSubmit" runat="server" CommandName="Submit" Text="Action" CommandArgument='<%# ((GridViewRow) Container).RowIndex %>' ></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>

VB.Net Code:

        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowCommand="GridView1_RowCommand" HeaderStyle-BackColor="CornflowerBlue" HeaderStyle-Font-Bold="true" HeaderStyle-ForeColor="White" CellPadding="5">
         <Columns>
             <asp:BoundField DataField="Name" HeaderText="Name" />
             <asp:BoundField DataField="Description" HeaderText="Description" />
             <asp:BoundField DataField="Brand" HeaderText="Brand" />

                <asp:TemplateField HeaderText="Submit" ItemStyle-HorizontalAlign="Center"> 
                <ItemTemplate> 
                <asp:LinkButton ID="lnkSubmit" runat="server" CommandName="Submit" Text="Action" CommandArgument='<%# CType(Container,GridViewRow).RowIndex %>' ></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:

C# Code:

    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.Equals("Submit"))
        {
            int RowIndex = Convert.ToInt32((e.CommandArgument).ToString());
            lblRowIndex.Text = "Row Index = " + RowIndex.ToString();
        }
    }

VB.Net Code:

    Protected Sub GridView1_RowCommand(sender As Object, e As GridViewCommandEventArgs)
        If e.CommandName.Equals("Submit") Then
            Dim RowIndex As Integer = Convert.ToInt32((e.CommandArgument).ToString())
            lblRowIndex.Text = "Row Index = " & RowIndex.ToString()
        End If
    End Sub

Hope now you can findout the RowIndex number of any row of the GridView whatever the control is. Happy coding !!

Download Code Example C#        Download Code Example VB.Net

4 thoughts on “How To Get RowIndex of Asp.Net GridView RowCommand Event C# VB.Net

  • January 24, 2015 at 8:21 am
    Permalink

    Thanks it is working for me. Great job

    Reply
  • June 9, 2015 at 3:52 pm
    Permalink

    Hi, how to trigger rowcommand event with enter key of the keyboard? can you help? Thanks.

    Reply
  • October 11, 2016 at 9:34 pm
    Permalink

    Nice job!! Thank you

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

AlphaOmega Captcha Classica  –  Enter Security Code