-3

I have a Form 1 that opens Form2. How I make all textBox readonly in Form2 opens?

Form 1:

Form2 f2 = new Form2();
f2.ReadOnly();
f2.ShowDialog();

Form 2:

public void ReadOnyTextBoxes(Control parent)
{
    foreach (Control c in parent.Controls)
    {
        if (c.GetType() == typeof(TextBox))
        {
            ((TextBox)(c)).ReadOnly = true;
        }
    }
}

public void ReadOnly()
{
     ReadOnyTextBoxes(groupBox1);
}
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Square Ponge
  • 702
  • 2
  • 10
  • 26

2 Answers2

2

there could be other groupboxes or some containers in groupbox1. you need recursion. How to disable all controls on the form except for a button?

Community
  • 1
  • 1
yavuz
  • 332
  • 1
  • 4
1

Working with your idea, in order to make it work on all TextBoxes you could do this with a recursive function, something like:

public void MakeReadOnlyTextBoxes(Control parent)
{
    foreach (Control c in parent.Controls)
    {
        if (c.GetType() == typeof(TextBox))
        {
            ((TextBox)(c)).ReadOnly = true;
        }
        else if(c.Controls.Count > 0)
        {
            MakeReadOnlyTextBoxes(c);
        }
    }
}

public void ReadOnly()
{
     ReadOnyTextBoxes(this);
}

Edited: you should use the c variable at the recursive call

Eyal H
  • 991
  • 5
  • 22