Wednesday 8 August 2012

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


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 in the RowCommand Event we have two options.

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:
GridView RowCommand to get RowIndex
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.

1 comments:

Anonymous said...

rows expanding in hierarchical gridview

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More