How do I find all the text boxes in a gridview row?

I have a GridView in a website that has different controls on each row (ex: textbox, label, dropdownlist). I need to find all the text boxes and set the enabled property to false so the user won't be able to edit them. I tried the code below but it doesn't work, "c" is never recognized as a text field, 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;
            }
        }
    }
}

      

+3


source to share


3 answers


I think you should try like this:



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

      

+2


source


Your text boxes should be nested within other controls, most likely in cells within a row. This is why you cannot find them by simply iterating through the immediate children.

If you have a list of textbox IDs you should use FindControl:

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

      

Otherwise, you need to recursively find the controls of the required type. See this thread for a sample code.



Another option, if a

relatively easy to compute, should be used directly in the markup, for example:

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

      

It depends a lot on how it turns out a

. If it is a protected or public field of a page class, only the code above should work. If it's calculated based on a string, you might need to include it in a protected method and pass parameters to it:

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

      

+1


source


And I also want to add some updates. There are various types of rows in the gridview (header, footer, datarow, etc.)

so to quickly find the control.

Try below (check 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;
            }
        }

      

+1


source







All Articles