[c#] ASP.NET GridView RowIndex As CommandArgument

How can you access and display the row index of a gridview item as the command argument in a buttonfield column button?

<gridview>
<Columns>
   <asp:ButtonField  ButtonType="Button" 
        CommandName="Edit" Text="Edit" Visible="True" 
        CommandArgument=" ? ? ? " />
.....

This question is related to c# asp.net gridview

The answer is


Here is Microsoft Suggestion for this http://msdn.microsoft.com/en-us/library/bb907626.aspx#Y800

On the gridview add a command button and convert it into a template, then give it a commandname in this case "AddToCart" and also add CommandArgument "<%# ((GridViewRow) Container).RowIndex %>"

<asp:TemplateField>
  <ItemTemplate>
    <asp:Button ID="AddButton" runat="server" 
      CommandName="AddToCart" 
      CommandArgument="<%# ((GridViewRow) Container).RowIndex %>"
      Text="Add to Cart" />
  </ItemTemplate> 
</asp:TemplateField>

Then for create on the RowCommand event of the gridview identify when the "AddToCart" command is triggered, and do whatever you want from there

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
  if (e.CommandName == "AddToCart")
  {
    // Retrieve the row index stored in the 
    // CommandArgument property.
    int index = Convert.ToInt32(e.CommandArgument);

    // Retrieve the row that contains the button 
    // from the Rows collection.
    GridViewRow row = GridView1.Rows[index];

    // Add code here to add the item to the shopping cart.
  }
}

**One mistake I was making is that I wanted to add the actions on my template button instead of doing it directly on the RowCommand Event.


with paging you need to do some calculation

int index = Convert.ToInt32(e.CommandArgument) % GridView1.PageSize;

void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
    Button b = (Button)e.CommandSource;
    b.CommandArgument = ((GridViewRow)sender).RowIndex.ToString();
}

I think this will work.

<gridview>
<Columns>

            <asp:ButtonField  ButtonType="Button" CommandName="Edit" Text="Edit" Visible="True" CommandArgument="<%# Container.DataItemIndex %>" />
        </Columns>
</gridview>

void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
    Button b = (Button)e.CommandSource;
    b.CommandArgument = ((GridViewRow)sender).RowIndex.ToString();
}

I think this will work.

<gridview>
<Columns>

            <asp:ButtonField  ButtonType="Button" CommandName="Edit" Text="Edit" Visible="True" CommandArgument="<%# Container.DataItemIndex %>" />
        </Columns>
</gridview>

MSDN says that:

The ButtonField class automatically populates the CommandArgument property with the appropriate index value. For other command buttons, you must manually set the CommandArgument property of the command button. For example, you can set the CommandArgument to <%# Container.DataItemIndex %> when the GridView control has no paging enabled.

So you shouldn't need to set it manually. A row command with GridViewCommandEventArgs would then make it accessible; e.g.

protected void Whatever_RowCommand( object sender, GridViewCommandEventArgs e )
{
    int rowIndex = Convert.ToInt32( e.CommandArgument );
    ...
}

I think this will work.

<gridview>
<Columns>

            <asp:ButtonField  ButtonType="Button" CommandName="Edit" Text="Edit" Visible="True" CommandArgument="<%# Container.DataItemIndex %>" />
        </Columns>
</gridview>

<asp:LinkButton ID="LnkBtn" runat="server" Text="Text" RowIndex='<%# Container.DisplayIndex %>' CommandArgument='<%# Eval("??") %>' OnClick="LnkBtn_Click" />

inside your event handler :

Protected Sub LnkBtn_Click(ByVal sender As Object, ByVal e As EventArgs)
  dim rowIndex as integer = sender.Attributes("RowIndex")
  'Here you can use also the command argument for any other value.
End Sub

<asp:TemplateField HeaderText="" ItemStyle-Width="20%" HeaderStyle-HorizontalAlign="Center">
                    <ItemTemplate>
                        <asp:LinkButton runat="server" ID="lnkAdd" Text="Add" CommandName="Add" CommandArgument='<%# Eval("EmpID"))%>' />
                    </ItemTemplate>
                </asp:TemplateField>

This is the traditional way and latest version of asp.net framework having strongly typed data and you don't need to use as string like "EMPID"


<asp:LinkButton ID="LnkBtn" runat="server" Text="Text" RowIndex='<%# Container.DisplayIndex %>' CommandArgument='<%# Eval("??") %>' OnClick="LnkBtn_Click" />

inside your event handler :

Protected Sub LnkBtn_Click(ByVal sender As Object, ByVal e As EventArgs)
  dim rowIndex as integer = sender.Attributes("RowIndex")
  'Here you can use also the command argument for any other value.
End Sub

I typically bind this data using the RowDatabound event with the GridView:

protected void FormatGridView(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
   if (e.Row.RowType == DataControlRowType.DataRow) 
   {
      ((Button)e.Row.Cells(0).FindControl("btnSpecial")).CommandArgument = e.Row.RowIndex.ToString();
   }
}

Here is Microsoft Suggestion for this http://msdn.microsoft.com/en-us/library/bb907626.aspx#Y800

On the gridview add a command button and convert it into a template, then give it a commandname in this case "AddToCart" and also add CommandArgument "<%# ((GridViewRow) Container).RowIndex %>"

<asp:TemplateField>
  <ItemTemplate>
    <asp:Button ID="AddButton" runat="server" 
      CommandName="AddToCart" 
      CommandArgument="<%# ((GridViewRow) Container).RowIndex %>"
      Text="Add to Cart" />
  </ItemTemplate> 
</asp:TemplateField>

Then for create on the RowCommand event of the gridview identify when the "AddToCart" command is triggered, and do whatever you want from there

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
  if (e.CommandName == "AddToCart")
  {
    // Retrieve the row index stored in the 
    // CommandArgument property.
    int index = Convert.ToInt32(e.CommandArgument);

    // Retrieve the row that contains the button 
    // from the Rows collection.
    GridViewRow row = GridView1.Rows[index];

    // Add code here to add the item to the shopping cart.
  }
}

**One mistake I was making is that I wanted to add the actions on my template button instead of doing it directly on the RowCommand Event.


I typically bind this data using the RowDatabound event with the GridView:

protected void FormatGridView(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
   if (e.Row.RowType == DataControlRowType.DataRow) 
   {
      ((Button)e.Row.Cells(0).FindControl("btnSpecial")).CommandArgument = e.Row.RowIndex.ToString();
   }
}

I typically bind this data using the RowDatabound event with the GridView:

protected void FormatGridView(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
   if (e.Row.RowType == DataControlRowType.DataRow) 
   {
      ((Button)e.Row.Cells(0).FindControl("btnSpecial")).CommandArgument = e.Row.RowIndex.ToString();
   }
}

<asp:TemplateField HeaderText="" ItemStyle-Width="20%" HeaderStyle-HorizontalAlign="Center">
                    <ItemTemplate>
                        <asp:LinkButton runat="server" ID="lnkAdd" Text="Add" CommandName="Add" CommandArgument='<%# Eval("EmpID"))%>' />
                    </ItemTemplate>
                </asp:TemplateField>

This is the traditional way and latest version of asp.net framework having strongly typed data and you don't need to use as string like "EMPID"


MSDN says that:

The ButtonField class automatically populates the CommandArgument property with the appropriate index value. For other command buttons, you must manually set the CommandArgument property of the command button. For example, you can set the CommandArgument to <%# Container.DataItemIndex %> when the GridView control has no paging enabled.

So you shouldn't need to set it manually. A row command with GridViewCommandEventArgs would then make it accessible; e.g.

protected void Whatever_RowCommand( object sender, GridViewCommandEventArgs e )
{
    int rowIndex = Convert.ToInt32( e.CommandArgument );
    ...
}

with paging you need to do some calculation

int index = Convert.ToInt32(e.CommandArgument) % GridView1.PageSize;

I think this will work.

<gridview>
<Columns>

            <asp:ButtonField  ButtonType="Button" CommandName="Edit" Text="Edit" Visible="True" CommandArgument="<%# Container.DataItemIndex %>" />
        </Columns>
</gridview>

void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
    Button b = (Button)e.CommandSource;
    b.CommandArgument = ((GridViewRow)sender).RowIndex.ToString();
}

I typically bind this data using the RowDatabound event with the GridView:

protected void FormatGridView(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
   if (e.Row.RowType == DataControlRowType.DataRow) 
   {
      ((Button)e.Row.Cells(0).FindControl("btnSpecial")).CommandArgument = e.Row.RowIndex.ToString();
   }
}

void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
    Button b = (Button)e.CommandSource;
    b.CommandArgument = ((GridViewRow)sender).RowIndex.ToString();
}

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