itzArun
itzArun

Reputation: 691

How to make readonly to multiple textboxes

I got this script while searching through stackoverflow

string commonTextBoxPrefix = "txt";
            foreach (Control c in this.Controls)
            {
                if (c.GetType() == typeof(TextBox) && 
                    c.ID.StartsWith(commonTextBoxPrefix))
                {
                    ((TextBox)c).ReadOnly = true;
                }
            }

But when I loop through the controls its not detecting any other controls, it detects only {System.Web.UI.LiteralControl} So the loop no entering into

if (c.GetType() == typeof(TextBox)

Why the code not detecting Textboxes and other control. I tried the below code also

foreach (Control c in parent.Controls)
        {
            if (c.Controls.Count > 0)
            {
                ClearControls(c);
            }
            else
            {
                switch (c.GetType().ToString())
                {
                    case "System.Web.UI.WebControls.TextBox":
                        ((TextBox)c).Text = "";
                        break;
                    case "System.Web.UI.WebControls.CheckBox":
                        ((CheckBox)c).Checked = false;
                        break;
                    case "System.Web.UI.WebControls.RadioButton":
                        ((RadioButton)c).Checked = false;
                        break;
                    case "System.Web.UI.WebControls.DropDownList":
                        ((DropDownList)c).SelectedIndex = -1;
                        break;
                }
            }
        }

But the loop not lets in to the conditions. Why the loop not detecting Textboxes? How can I set multiple textboxes to readonly.?

Upvotes: 2

Views: 2756

Answers (2)

igofed
igofed

Reputation: 1442

There can be some controls encapsulated into anothers. So here is recoursive method to do you want:

void DoReadOnly(Control control)
{
    foreach (Control c in control.Controls)
    {
        if (c.Controls != null && c.Controls.Count > 0)
        {
            DoReadOnly(c);
        }
        else if (c is TextBox)
        {
            (c as TextBox).ReadOnly = true;
        }
    }
}

You should call it in such way:

DoReadOnly(this.Form);

Hope it will help you.

Upvotes: 3

Developer
Developer

Reputation: 8636

Works for me

<asp:Panel ID="Panel1" runat="server">
            <asp:TextBox ID="txt1" runat="server"></asp:TextBox>
            <asp:TextBox ID="txt2" runat="server"></asp:TextBox>
            <asp:TextBox ID="txt3" runat="server"></asp:TextBox>
</asp:Panel>

 protected void Page_Load(object sender, EventArgs e)
{
    ClearTextBoxes(Panel1);
}
protected void ClearTextBoxes(Control control)
{
    foreach (Control c in control.Controls)
    {
        if (c is TextBox && c.ID.StartsWith("txt"))
            ((TextBox)c).ReadOnly = true;
    }
}

enter image description here

Upvotes: 4

Related Questions