简体   繁体   中英

Setting readonly for all textboxes C# ASP.NET

Can anyone suggest a way to set readonly of all textboxes . I tried using aa recursive function but it will say that System.Web.UI.Control has no such definition for ReadOnly

    private void SetReadOnly<T>(Control parent, bool isReadOnly)
{
    foreach (Control ctrl in parent.Controls)
    {
        if (ctrl is T)
            ctrl.ReadOnly = isReadOnly;   // this line here wont work .
        SetReadOnly<T>(ctrl, isReadOnly);
    }
}

Any alternatives please !!

The problem with your code is that T can be any type and not all types have the property ReadOnly . Hence the compiler will choke.

You don't need to use generics to do this:

private void SetReadOnly(Control parent, bool readOnly)
{
  // Get all TextBoxes and set the value of the ReadOnly property.
  foreach (var tb in parent.Controls.OfType<TextBox>())
    tb.ReadOnly = readOnly;

  // Recurse through all Controls
  foreach(Control c in parent.Controls)
    SetReadOnly(c, readOnly);
}

If you however would like to use generics you can do it like this:

private void SetReadOnly<T>(Control parent, bool readOnly) where T : TextBox
{
  // Get all TextBoxes and set the value of the ReadOnly property.
  foreach (var tb in parent.Controls.OfType<T>())
    tb.ReadOnly = readOnly;

  // Recurse through all Controls
  foreach(Control c in parent.Controls)
    SetReadOnly<T>(c, readOnly);
}

This will constrain the generic type to TextBox or any class derived from it . This assures that the ReadOnly property will always be there and the compiler knows this.

You can set this on the client side using jQuery:

 $(document).ready(function() {
   $('input[type=text]').attr('readonly', true);
 });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM