private void Page_Load(object sender, System.EventArgs e)
{
// 在此处放置用户代码以初始化页面
Response.Write(GetControlsAttribute());
} public ControlCollection GetControls(){
ControlCollection cc = this.CreateControlCollection();
for (int i = 0; i < Page.Controls.Count;i++){
if (Page.Controls[i].ID != null){
cc.Add(Page.Controls[i]);
}
foreach(Control control in Page.Controls[i].Controls){
if (control.ID != null){
cc.Add(control);
}
}
}
return cc;
} public string GetControlsAttribute(){
string strControl = "";
ControlCollection cc = GetControls();
for (int i = 0; i < cc.Count;i++){
strControl += strControl + cc[i].ID.ToString() + ":" + cc[i].GetType().ToString() + ",";
}
return strControl;
}
Exception Details: System.InvalidOperationException: The list that this enumerator is bound to has been modified. An enumerator can only be used if the list doesn't change.Line 62:  foreach(Control control in Page.Controls[i].Controls){

解决方案 »

  1.   

    Exception Details: System.InvalidOperationException: The list that this enumerator is bound to has been modified. An enumerator can only be used if the list doesn't change.Line 62:  foreach(Control control in Page.Controls[i].Controls){
      

  2.   

    don't use foreach, if you are doing cc.Add, you are also remove the control from Page.Controls[i].Controls, that is not allowed, try something like
    int j=0;while (j < Page.Controls[i].Controls.Count)
    {
       Control control = Page.Controls[i].Controls[j];
       if (control.ID != null) cc.Add(control);
       else j++;
    }
      

  3.   

    thanks我想实现的目的是:获得页面上所有的控件,从而获得各个控件的id及控件类型 public ControlCollection GetControls(){
    ControlCollection cc = this.CreateControlCollection();
    for (int i = 0; i < Page.Controls.Count;i++){
    if (Page.Controls[i].ID != null){
    cc.Add(Page.Controls[i]);
    int j = 0;
    while(j < Page.Controls[i].Controls.Count){
    Control control = Page.Controls[i].Controls[j];
    if (control.ID != null) cc.Add(control);
    else j++;
    }
    }
    }
    return cc;
    } public string GetControlsAttribute(){
    string strControl = "";
    ControlCollection cc = GetControls();
    for (int i = 0; i < cc.Count;i++){
    strControl += strControl + cc[i].ID.ToString() + ":" + cc[i].GetType().ToString() + ",";
    }
    return strControl;
    }这样GetControlsAttribute()方法获得的值为空,但实际上我页面上有很多控件,包括自定义控件,用户控件,web控件
      

  4.   

    而GetControls()这个方法获得ControlCollection好像也是为空的
      

  5.   

    为什么Page.Controls[i].ID总是为空的?
      

  6.   

    void GetControlsInfo(Control c, System.Text.StringBuilder sb)
    {
      sb.AppendFormat("ID:{0}:Type:{1} --- ", c.ID, c.GetType().Name);
      foreach(Control cc in c.Controls)
    GetControlsInfo(cc,sb);
    }
    ...System.Text.StringBuilder sb = new System.Text.StringBuilder();
    GetControlsInfo(Page,sb);
    Response.Write(sb.ToString());