【问题标题】:Set all texbox readonly将所有文本框设置为只读
【发布时间】:2017-05-22 15:31:46
【问题描述】:

如何设置 onload all TextBox readonly from masterpage code behind?

我尝试了下面的代码,但它不起作用:

protected void Page_Load(object sender, EventArgs e)
{
   foreach (Control c in this.Controls)
   {
     if (c is TextBox)
        ((TextBox)c).ReadOnly = true;
   }
}

谢谢

【问题讨论】:

  • 你错过了控件中的控件:void foo(Control p){foreach(Control c in p.Controls) if( c is TextBox ) ((TextBox)c).ReadOnly = true; else foo(c);} 并不是我真的建议这样做。比在 .Controls 中搜索要好得多。

标签: c# asp.net textbox code-behind


【解决方案1】:

Ebyrob 和我有同样的想法,添加了空引用保护并检查控件是否有子控件(减少调用)。

  protected void Page_Load(object sender, EventArgs e)
    {
        SetReadonly(this);
    }
    private void SetReadonly(Control c)
    {
        if (c == null)
        {
            return; 
        }
        foreach (Control item in c.Controls)
        {
            if (item.HasChildren)
            {
                SetReadonly(c);
            }
            else if (c is TextBox)
            {
                ((TextBox)c).ReadOnly = true;
            }

        }
    }

【讨论】:

  • @Amid,确保您有“使用 System.Windows.Forms”,Control.HasChildren 自 1.1 link 以来一直是 .Net 框架的一部分,并且自 4.5 起仍在框架中。此具体示例在 4.0 中进行了测试。
【解决方案2】:

试试:

protected void Page_Load(object sender, EventArgs e)
{
  foreach (TextBox textbox in this.Controls.OfType<TextBox>())
   {
        textbox.ReadOnly = true;
   }
}

【讨论】:

    【解决方案3】:

    试试这个。我对此进行了测试并且工作正常

     private void SetReadonly(Control c)
        {
            if (c == null)
            {
                return;
            }
            foreach (Control item in c.Controls)
            {
    
                if (item is TextBox)
                {
                    ((TextBox)item).ReadOnly = true;
                }
    
                else if (item.HasControls())
                {
                    SetReadonly(item);
                }
    
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-02-02
      • 1970-01-01
      • 2014-01-28
      • 2023-01-03
      • 2020-04-12
      • 1970-01-01
      • 2018-05-09
      相关资源
      最近更新 更多