C# 将多个控件的特殊属性设置为相同的值
如何将多个控件的特殊属性设置为相同的值? 例如,将表单中所有标签的C# 将多个控件的特殊属性设置为相同的值,c#,asp.net,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 =
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;
}
}
受保护的无效页面加载(对象发送方,事件参数e)
{
foreach(this.Controls.OfType()中的标签lbl){
如果(lbl==null)继续;
lbl.可见=假;
}
}
我应该提到我使用母版页,但我不想设置嵌套母版页的属性。我只想设置当前ASP页面的属性。您可能在其他页面中有一些控件,因此您需要重复调用它……下面是我使用的类似方法 请注意,在最后,如果所讨论的控件有自己的控件,我从其内部调用它 希望这有助于
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);
}
}
}
请注意,您可以使用以下方法来避免这种丑陋的类型检查:
foreach(Label lbl in this.Controls.OfType<Label>())
lbl.Visible= false;
然后,此可读代码应隐藏页面上和母版页中的所有标签:
var allLabels = this.GetControlsRecursively()
.Concat(this.Master.GetControlsRecursively())
.OfType<Label>();
foreach (Label label in allLabels)
label.Visible = false;
var allLabels=this.getControlsRecursive()
.Concat(this.Master.getControlsRecursive())
.of type();
foreach(所有标签中的标签)
标签可见=假;
var allLabels = this.GetControlsRecursively()
.Concat(this.Master.GetControlsRecursively())
.OfType<Label>();
foreach (Label label in allLabels)
label.Visible = false;
protected void Page_Load(object sender, EventArgs e)
{
SetAllLabelValue(this.Controls);
}
private void SetAllLabelValue(ControlCollection controls)
{
foreach (Control item in controls)
{
if (item.HasControls())
{
SetAllLabelValue(item.Controls);
}
Label lb = item as Label;
if (lb != null)
{
lb.Visible = false;
}
}
}