Amit
Amit

Reputation: 22086

How to find all controls in Gridview?

I have a gridview which contains controls like checkbox dropdownlist textbox etc.. These controls are in TemplateField and some are in updatepanel in gridview. There is a EditTemplateField which has some controls and a button. When grid is in edit mode, Now I have to find all controls in this EditTemplateField in button click event. I know that this can be done using foreach loop but don't know how?

Upvotes: 0

Views: 23426

Answers (4)

Chris Mullins
Chris Mullins

Reputation: 6867

You can use the grid EditIndex to find the row that contains the controls that are in edit mode. From there you can get the control using the control ID.

TextBox txtItem = (TextBox)Grid1.Rows[Grid1.EditIndex].FindControl("txtItem");

To find all controls then try this:

foreach(Control c in Grid1.Rows[Grid1.EditIndex].Controls)
{
    // do stuff in here.

}

If you have container controls in the row, and need to find things inside of them, then you need do do something to recurse down into their controls.

I don't understand though why you would need to loop though the controls, usually the controls in the edit template will be fixed, and you know what they are so accessing them directly with Findcontrol is the way to go.

Upvotes: 4

James McCormack
James McCormack

Reputation: 9954

Here's a nifty utility method. It's recursive so it will find nested stuff e.g.

var listOfControls = Utility.FindControlsOfType<TextBox>(yourGridRow);

If you don't know the exact type of the nested controls, use FindControlsOfType<WebControl> instead.

public static class Utility
{    
    public static List<T> FindControlsOfType<T>(Control ctlRoot)
    {
        List<T> controlsFound = new List<T>();

        if (typeof(T).IsInstanceOfType(ctlRoot))
            controlsFound.Add((T)(object)ctlRoot);

        foreach (Control ctlTemp in ctlRoot.Controls)
        {
            controlsFound.AddRange(FindControlsOfType<T>(ctlTemp));
        }

        return controlsFound;
    }
}

Upvotes: 1

ibram
ibram

Reputation: 4579

If you mean in code you can do it like this:

foreach ( GridViewRow row in MyGridView.Rows )
{
    TextBox myTextBox = (TextBox)row.FindControl("myTextBox");
}

Upvotes: 2

dhinesh
dhinesh

Reputation: 4764

Take the generated html using Firebug and using http://jsfiddle.net you can include jquery and play with the html.

Add the event handler to the edit button like

For example

function edit(this)
{
   var textboxID = $(this).parent().find("[id$='textBoxId']");
}

Upvotes: 0

Related Questions