如何将多个控件的特殊属性设置为相同的值?
例如,将表单中所有标签的 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 页面的属性。
最佳答案
你可能在其他人中有一些控件,所以你需要递归地调用它....这是我使用的一个类似的方法......................
注意最后,如果有问题的控件有自己的控件,我会从自身内部调用它......
希望这对你有帮助......
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);
}
}
}
关于c# - 将多个控件的特殊属性设置为相同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35476050/