C# – Get current GridView column value

asp.netcgridview

I have GridView with some of columns. all the columns are boundfield like:

            <asp:BoundField DataField="orderId" HeaderText="orderId" 
            SortExpression="orderId"></asp:BoundField>

The last column is:

                    <asp:LinkButton ID="LinkButton1" runat="server"    
  CommandName="" onclick="LinkButton1_Click" Text="Button"></asp:LinkButton>

as you see , there is "onclick" with some method.. like:

        lbltest.Text = gv_order.Rows[gv_order.SelectedIndex].Cells[2].Text;

With that code i get (offcourse) what i have on the selected row in cell number 2. how can i get value from the same row (and from cell number 2) where the button is clicked without the "selceted row" ? example: when i click button on row 2 – i get the cell 2 of that row.

That's possible?

Best Answer

If you want to retrieve 'orderid' in more clean way, you can use CommandName, CommandArgument properties and OnRowCommand event like this:

        <asp:GridView (...) OnRowCommand="Gv_RowCommand" (...)>

...

        <asp:LinkButton ID="LinkButton1" runat="server" CommandName="Select"
     CommandArgument='<%# Bind("orderId") %>' Text="Button"></asp:LinkButton>

and in code behind:

protected void Gv_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName == "Select")
    {
         int selectedOrderId = Convert.ToInt32(e.CommandArgument);
         // ... 
    }
}

I hope this is what you want to do.

Edit - my answer to your comment:

Then, it's little more complicated and uses 'selectedRow' in some way. In my own code, I use this approach:

    <asp:GridView ID="gv1" (...) DataKeyNames="orderId,email,username"
         OnRowCommand="Gv_RowCommand" (...)>

            ...

    <asp:LinkButton ID="LinkButton1" runat="server" CommandName="Select"
       CommandArgument='<%# DataBinder.Eval(Container,"RowIndex") %>' Text="Button">
</asp:LinkButton>

and in code behind:

protected void Gv_RowCommand(object sender, GridViewCommandEventArgs e)
{
    int selectedRowIndex = Convert.ToInt32(e.CommandArgument);
    if (e.CommandName == "Select")
    {
         int orderId = Convert.ToInt32(gv1.DataKeys[selectedRowIndex]["orderId"]);
         string email = gv1.DataKeys[selectedRowIndex]["email"].ToString();
         // ... 
    }
}