Adam Miklosi
Adam Miklosi

Reputation: 762

How to find all textboxes in a gridview row?

I have a GridView on a website, that have different controls in each row (eg.: textbox, label, dropdownlist). I need to find all textboxes and set the enabled property to false, so the user won't be able to edit them. I tried the code below, but it dosn't work, 'c' never recognised as a textbox, so it never changes the property.

protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
    if (a)
    {
        foreach (Control c in e.Row.Controls)
        {
            if (c is TextBox)
            {
                ((TextBox)(c)).Enabled = false;
            }
        }
    }
}

Upvotes: 4

Views: 2721

Answers (4)

sachindaK
sachindaK

Reputation: 31

You should search controls inside the cell instead of Row.

foreach (TableCell cell in e.Row.Cells)
{
     foreach (Control c in cell.Controls)
     {
           if (c is TextBox)
           {
                  ((TextBox)(c)).Enabled = false;
           }
     }
}

Upvotes: 0

Komal
Komal

Reputation: 304

And also want to put some updation. There are different types of rows in gridview (header,footer,datarow,etc)

so for making little faster for the control find.

Try below (check the if condition)

protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                //Find the TextBox control.
                TextBox txtName = (e.Row.FindControl("txtName") as TextBox);
                txtName.Enabled = false;

                //or
                TextBox txtName1 = (TextBox)e.Row.FindControl("txtName");
                txtName1.Enabled = false;
            }
        }

Upvotes: 1

I think you should try like this:

TextBox tb = e.Row.FindControl("textbox_name") as TextBox;
tb.Enabled = false;

Upvotes: 3

Andrei
Andrei

Reputation: 56696

Your textboxes must be nested within other controls, most likely cells inside the row. That is why you cannot find them just iterating through immediate children.

If you have a list of IDs of the text boxes, you should use FindControl:

((TextBox)e.Row.FindControl("TextBoxID")).Enabled = false;

Otherwise you will need to recursively find your controls of necessary type. See this thread for code sample.

One more option, if a is relatively easy to calculate, is to use in the markup directly, like so:

<asp:TextBox ... Enabled='<%# a %>' />

This depends a lot on the details of how a is derived. If it is a protected or public field of the page class, just the code above should work. If it is calculated based on row, you may need to turn it into protected method and pass params into it:

Enabled='<%# GetEnabled(Eval("Prop1"), Eval("Prop2")) %>'

Upvotes: 1

Related Questions