How to change readonly false property of text fields in winform?

How can we change the ReadOnly property for all text fields in winform, which is true for false, I try to use this code, but it causes me a null null reference reference error ...

    private void TextBoxesReadOnlyTrue(Control.ControlCollection cc)
    {
        foreach (Control ctrl in cc)
        {
            TextBox tb = ctrl as TextBox;
            if (tb.ReadOnly)
             {
                tb.ReadOnly = false;
             }

        }
    } 
+4
source share
2 answers

This is because not all controls in cc are TextBoxes. Therefore, when you try to convert them to a TextBox, the variable is null. When a variable is null, you cannot access any properties of this variable or you will get an error. Therefore, at any time, the variable can be zero, you must first check whether it is zero.

if, , :

    if (tb != null && tb.ReadOnly) { tb.ReadOnly = false; }

, , , . , , : 1: GroupBox. -. . , , . - , Controls. , , ( ) , . ( , Controls, , .) :

private void TextBoxesReadOnlyTrue(Control.ControlCollection cc)
{
    foreach (Control ctrl in cc)
    {
        TextBox tb = ctrl as TextBox;
        if (tb != null && tb.ReadOnly)
        { tb.ReadOnly = false; continue; }

        if (ctrl.Controls != null && ctrl.Controls.Count > 0)
        { TextBoxesReadOnlyTrue(ctrl.Controls); }
        // this recursively calls this same method for every control ...
        // that is a container control that contains more controls, ...
        // such as GroupBoxes, Panels, etc.
    }
}
+6

​​:

private IEnumerable<T> GetControls<T>(Control.ControlCollection ctrls)
{
    foreach (object ctrl in ctrls)
    {
        foreach (var item in GetControls<T>(((Control)ctrl).Controls))
        {
            yield return item;    
        } 
        if (ctrl is T)
           yield return (T)ctrl;

    }
}

foreach(var txtbox in  GetControls<TextBox>(form.Controls)
{
    txtbox.ReadOnly = false;
}
+2

All Articles