How to pass the rownumber of a gridview as a commandargument using asp.net?

3.3k Views Asked by At

I am a beginner when it comes to asp.net. I am trying since yesterday to find the answer to a question: How can I pass the rownumber of a gridview as a commandargument using asp.net?

I have tried many methods/ways, but none worked (the commandargument is null in code-behind), so I thought it would be proper to try with a javascript function (if there's a shorter,clearer way than using javascript, please tell me).

Here's the function :

     <script type = "text/javascript">
   function GetSelectedRow(lnk) {
       var row = lnk.parentNode.parentNode;
       var rowIndex = row.rowIndex - 1;
       alert("RowIndex: " + rowIndex);
       return rowIndex;
   }
</script>

And also:

    <ItemTemplate>
                <asp:Label ID="labelStatus" 
                           runat="server" 
                           Text='<%#Bind("Statut")%>'
                           CommandArgument='<%#"Eval(GetSelectedRow(lnk))"%>'>
                </asp:Label>
   </ItemTemplate>

The reason I need the row number is in OnRowCommand event handler, in order to be able to specify which row is being edited. ( myGridView.EditIndex = Convert.Int16(e.CommandArgument.ToString()); ).

Thank you in advance :)

2

There are 2 best solutions below

1
On

you find here an full example about GridView and OnRowCommand

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.onrowcommand.aspx

3
On

You can do it on a server side in RowCreated handler:

protected void GridView1_RowCreated(Object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        // Find the control which fires the command
        LinkButton button = (LinkButton)e.Row.Cells[0].FindControl("LinkButton1");

        button.CommandArgument = e.Row.RowIndex.ToString();
    }
}

Now after LinkButton1 is clicked the RowCommand event will be triggered, and you can access this CommandArgument in the handler:

protected void GridView1_RowCommand(Object sender, GridViewCommandEventArgs e)
{
    int rowIndex;
    if (int.TryParse(e.CommandArgument as string, out rowIndex))
    {
        // Do something with row index
    }
}