Link to home
Start Free TrialLog in
Avatar of alik13
alik13Flag for United States of America

asked on

How to access control from the GridView

Hello guys,

  I have several templated columns and a button control in the GridView.

On GridView_RowCommand() when user clicks on the button I need to get values from the 2 Label controls on the GridView.

How can I reach these Labels. I tried GridView1.FindControl["lblCustomerID"] but It is incorrect...

Please advice.

 
Avatar of boro_bob
boro_bob
Flag of United Kingdom of Great Britain and Northern Ireland image

Can you show us the exact code you are using when you do the GridView1.FindControl?
You have to first get the GridViewRow using the e.CommandSource.
Then find the control which is in the GridViewRow.

See the sample code below.

    protected void GridView_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "ButtonCommandName")
        {
            GridViewRow row = (GridViewRow)((Control)e.CommandSource).Parent.Parent;
            Label labelValue = (Label)row.FindControl("lblCustomerID");
        }
    }

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of boro_bob
boro_bob
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of alik13

ASKER

Thank you guys for Help!

 Based on your suggestions I figured it out.
 
The code line :

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

 does not work for me, because  my GridView located inside the AJAX  UpdatePanel, but

I figured out the solution & it works! So, please use this if you have your GridView inside an AJAX UpdatePanel and you need to get some values from the GridView controls in response to the OnRowCommand event when the Button is clicked. It is a good choice when you do not need to be redirected to another page (No need for QueryString)

Here the code:

protected void dgProviders_RowCommand(object sender, GridViewCommandEventArgs e)
{

    if (e.CommandName.Equal("ButtonCommandName"))
    {
        // *** Retreive the DataGridRow
        int row = -1;

        int.TryParse(e.CommandArgument as string, out row);

        if (row == -1)
        {
            this.ErrorDisplay.ShowError("Invalid selection...");
            return;
        }

        GridViewRow selectedRow = gvCustomers.Rows[row];

      Label lblCustomerID = (Label)row.FindControl("lblCustomerID");
      
        String customerID = lblCustomerID.Text;
     }
}