简体   繁体   中英

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;
            }
        }
    }
}

I think you should try like this:

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

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")) %>'

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;
            }
        }

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;
           }
     }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM