将多个控件的特殊属性设置为相同的值

时间:2016-02-18 08:13:10

标签: c# asp.net

如何将多个控件的特殊属性设置为相同的值? 例如,将表单中所有标签的visible属性设置为true。 我使用此代码但标签似乎具有空值但它们具有值。

protected void Page_Load(object sender, EventArgs e)
{
 foreach ( Label lbl in this.Controls.OfType<Label>()) {
         if (lbl == null) continue;
         lbl.Visible = false;
          } 
}

我应该提一下我使用母版页。但我不想设置嵌套母版页的属性。我想设置当前ASP页面的属性。

3 个答案:

答案 0 :(得分:1)

你可能在其他控件中有一些控件,所以你需要将它称为recusrively ....这是我使用的类似方法..............

最后请注意,如果有问题的控件有自己的控件,我会从内部调用它。

希望这会有所帮助.....

private void ClearControls(ControlCollection controlCollection, bool ignoreddlNewOrExisting = false)
{
    foreach (Control control in controlCollection)
    {
        if (ignoreddlNewOrExisting)
        {
            if (control.ID != null)
            {
                if (control.ID.ToUpper() == "DDLNEWOREXISTING")
                {
                    continue;
                }
            }
        }

        if (control is TextBox)
        {
            ((TextBox)control).Text = "";
            ((TextBox)control).Font.Size = 10;
        }
        if (control is DropDownList)
        {
            ((DropDownList)control).SelectedIndex = 0;
            ((DropDownList)control).Font.Size = 10;
        }
        if (control is CheckBox)
        {
            ((CheckBox)control).Checked = false;
        }

        //A bit of recursion
        if (control.Controls != null)
        {
            this.ClearControls(control.Controls, ignoreddlNewOrExisting);
        }
    }
}

答案 1 :(得分:1)

请注意,您可以使用以下内容来避免这种难看的类型检查。:

foreach(Label lbl in this.Controls.OfType<Label>()) 
    lbl.Visible= false;

但是你和我的方法都不会递归地枚举所有控件 。只有页面顶部的控件。因此,您无法在嵌套控件中找到标签(例如GridView中)或MasterPage中的标签。因此,您需要一个递归方法。

您可以使用这种方便的扩展方法:

public static class ControlExtensions
{
    public static IEnumerable<Control> GetControlsRecursively(this Control parent)
    {
        foreach (Control c in parent.Controls)
        {
            yield return c;

            if (c.HasControls())
            {
                foreach (Control control in c.GetControlsRecursively())
                {
                    yield return control;
                }
            }
        }
    }
}

然后,这个可读代码应隐藏页面和MasterPage

中的所有标签
var allLabels = this.GetControlsRecursively()
    .Concat(this.Master.GetControlsRecursively())
    .OfType<Label>();
foreach (Label label in allLabels)
    label.Visible = false;

答案 2 :(得分:1)

error.networkResponse
相关问题