Make all controls inside a GroupBox read-only?

Ahmad picture Ahmad · Mar 24, 2013 · Viewed 11.1k times · Source

I know that many individual controls have a ReadOnly property. But suppose I have a GroupBox in which there are many different controls (text boxes, combo boxes, radio buttons, etc ..), is it possible to set the ReadOnly property for all these controls together?

Not that I only want to set this property for the controls within a specific GroupBox (because I have multiple GroupBoxes too, so I don't want the setting to be done for controls in other GroupBoxes) ..

Manually setting the ReadOnly property seems very lethargic, as I have as many as 20 controls in each Groupbox (don't ask why :p).

Answer

Daniil picture Daniil · Mar 24, 2013

For standart controls in Winform you can use something like this (TextBoxBase is base class for ReadOnly properties controls) :

    private void button1_Click(object sender, EventArgs e)
    {
        SetReadonlyControls(groupBox1.Controls);
    }

    private void SetReadonlyControls(Control.ControlCollection controlCollection)
    {
        if (controlCollection == null)
        {
            return;
        }

        foreach (TextBoxBase c in controlCollection.OfType<TextBoxBase>())
        {
            c.ReadOnly = true;
        }
    }