asp遍历前端的所有控件

//遍历ID为Panel1的panel里的所有label控件

foreach (Control ctl in this.Panel1.Controls)
{

//判断类型为Label的
if (ctl.GetType() == typeof(Label))
{
//排除不需要的label
if (ctl.ID != "label1" && ctl.ID != "label2" && ctl.ID != "label3")
{

//将取到的控件赋给lb,记得加强制类型转换
Label lb = (Label)ctl;
//给所有label添加点击事件
lb.Attributes.Add("onclick", "alert('" + lb.Text.Trim() + "')");
}
}
}

//注意:如果label不是刚开始就有值的,则一定要把这段代码给label赋值语句之后,否则会取不到值

原文地址:https://www.cnblogs.com/haizine/p/7880743.html