Ghashgul
Ghashgul

Reputation: 97

Change all TextBox BorderStyle in my winform

How do i change all the borderstyle of textbox in winform by foreach

or something shorter then listing every textbox and change them.

Upvotes: 0

Views: 835

Answers (3)

Nicolas Tyler
Nicolas Tyler

Reputation: 10552

public void setAllTextBoxs(Control control)
{
    foreach (Control c in control.Controls)
        if (c is TextBox)
            (c as TextBox).BorderStyle = BorderStyle.FixedSingle;
        else if(c.HasChildren)
            setAllTextBoxs(c);
}

Lambda equivalent... old faithful one liner XD

public void setAllTextBoxs(Control control)
{
    control.Controls.Cast<Control>().ToList().ForEach(c => { if (c is TextBox) (c as TextBox).BorderStyle = BorderStyle.FixedSingle; else if (c.HasChildren) setAllTextBoxs(c); });
}

and call it like this:

setAllTextBoxs(this);

Upvotes: 0

Tobia Zambon
Tobia Zambon

Reputation: 7629

You can iterate through the form's controls:

foreach(Control c in myForm.Controls)
{ 
    if(c is TextBox)
    { 
         ((TextBox)c).BorderStyle = yourStyle;
    }
}

EDIT

if you have some containers that can contains TextBoxes (such as panels, tabControls, ecc..) you can iterate recursively:

private void checkControl(Control control)
{
    foreach (Control c in control.Controls)
    {
        var textBox = c as TextBox;
        if (textBox != null)
            textBox.BorderStyle = BorderStyle.FixedSingle;
        else
            checkControl(c);
    }
}

and initially call the method with:

checkControl(this);

Upvotes: 2

ojlovecd
ojlovecd

Reputation: 4902

private void SetTextBoxBorderStyle(Control ctrl)
{
    foreach(Control c in ctrl.Controls)
    {
        if(c is TextBox)
           (c as TextBox).BorderStyle = yourStyle;
        else
           SetTextBoxBorderStyle(c);
    }
}

Invoke it in your form like this:

SetTextBoxBorderStyle(this);

Upvotes: 0

Related Questions