Click here to Skip to main content
15,879,326 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
public void DisableControl(Control con)
{
foreach(Control c in con.Controls)
{
con.Enabled = false;

}
}

What I have tried:

method for disable only textbox in a form
Posted
Updated 14-Oct-17 20:08pm

1 solution

The code is the same, but you need to check "is this a textbox?" inside your loop:
foreach(Control c in con.Controls)
    {
    if (c is TextBox)
        {
        c.Enabled = false;
        }    
    }


Quote:
Can it Work when my textbox is in Panel

Depends on what you pass to your method: if it's the Form, then it won't - the Form.Controls collection contains the panel, and the Panel.Controls collection contains the TextBox so it won't get found.
If it's the Panel you pass then it will.

If you want to disable a textbox "somewhere in a control on the the form", then you need to call your method recursively:
C#
public void DisableControl(Control con)
    {
    foreach(Control c in con.Controls)
        {
        DisableControl(c);
        if (c is TextBox)
            {
            c.Enabled = false;
            }    
        }
    }
That will work if you pass it the form, and disable all textboxes on the form.
 
Share this answer
 
v2
Comments
Member 13224949 15-Oct-17 2:26am    
Can it Work when my textbox is in Panel
OriginalGriff 15-Oct-17 2:58am    
Answer updated.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900