We help IT Professionals succeed at work.

How to access control from the GridView

alik13
alik13 asked
on
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.

 
Comment
Watch Question

CERTIFIED EXPERT

Commented:
Can you show us the exact code you are using when you do the GridView1.FindControl?
Sachintana DissanayakeSenior Web Developer
CERTIFIED EXPERT

Commented:
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

CERTIFIED EXPERT
Commented:
That looks like it should work. When you say it is incorrect, what exactly is happening? When you debug it, step into that code. Is labelValue null?

Also, to actually get the value out of the label, you do realise you will need to add the line:

string textvalue = labelValue.Text;

Author

Commented:
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;
     }
}
Sachintana DissanayakeSenior Web Developer
CERTIFIED EXPERT

Commented:
Good Luck!!!

Explore More ContentExplore courses, solutions, and other research materials related to this topic.