[c#] Get Row Index on Asp.net Rowcommand event

I have an asp.net GridView:

<asp:TemplateField HeaderText="View Faktor" ShowHeader="False" Visible="True">
    <ItemTemplate>
        <asp:ImageButton ID="imgBtn1" CssClass="SelectRow" runat="server" CausesValidation="false"
            CommandArgument='<%#(eval("mprID")) %>' CommandName="ViewFactors" ImageUrl="~/tadarokat/Images/factor.png"
            Text="" />
    </ItemTemplate>
</asp:TemplateField>

How Can I get rowIndex on row command event?

I want to highlight (select) target row when RowCommand fires.

This question is related to c# asp.net gridview rowcommand

The answer is


I was able to use @rahularyansharma's answer above in my own project, with one minor modification. I needed to get the value of particular cells on the row on which the user clicks a LinkButton. The second line can be modified to get the value of as many cells as you wish.

Here is my solution:

GridViewRow gvr = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
string typecore = gvr.Cells[3].Text.ToString().Trim();

ImageButton \ Button etc.

CommandArgument='<%# Container.DataItemIndex%>' 

code-behind

protected void gvProductsList_RowCommand(object sender, GridViewCommandEventArgs e)
{
    int index = e.CommandArgument;
}

protected void gvProductsList_RowCommand(object sender, GridViewCommandEventArgs e)
{
    try
    {
        if (e.CommandName == "Delete")
        {
            GridViewRow gvr = (GridViewRow)(((ImageButton)e.CommandSource).NamingContainer);
            int RemoveAt = gvr.RowIndex;
            DataTable dt = new DataTable();
            dt = (DataTable)ViewState["Products"];
            dt.Rows.RemoveAt(RemoveAt);
            dt.AcceptChanges();
            ViewState["Products"] = dt;
        }
    }
    catch (Exception ex)
    {
        throw;
    }
}
protected void gvProductsList_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
    try
    {
        gvProductsList.DataSource = ViewState["Products"];
        gvProductsList.DataBind();
    }
    catch (Exception ex)
    {

    }
}

Or, you can use a control class instead of their types:

GridViewRow row = (GridViewRow)(((Control)e.CommandSource).NamingContainer);

int RowIndex = row.RowIndex; 

If you have a built-in command of GridView like insert, update or delete, on row command you can use the following code to get the index:

int index = Convert.ToInt32(e.CommandArgument);

In a custom command, you can set the command argument to yourRow.RowIndex.ToString() and then get it back in the RowCommand event handler. Unless, of course, you need the command argument for another purpose.


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to asp.net

RegisterStartupScript from code behind not working when Update Panel is used You must add a reference to assembly 'netstandard, Version=2.0.0.0 No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization How to use log4net in Asp.net core 2.0 Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state How to create roles in ASP.NET Core and assign them to users? How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause() ASP.NET Core Web API Authentication Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0 WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Examples related to gridview

Simple Android grid example using RecyclerView with GridLayoutManager (like the old GridView) Android Recyclerview GridLayoutManager column spacing Get the cell value of a GridView row add new row in gridview after binding C#, ASP.net Check if list is empty in C# How to refresh Gridview after pressed a button in asp.net Putting GridView data in a DataTable How to get row data by clicking a button in a row in an ASP.NET gridview Change header text of columns in a GridView Twitter Bootstrap and ASP.NET GridView

Examples related to rowcommand

Get Row Index on Asp.net Rowcommand event Get DataKey values in GridView RowCommand