我需要遍历所有的控件,我的asp网页,做一些事情来控制。在一种情况下我正在做一个巨大的串出页面,并通过电子邮件发送给自己,而在另一个情况下,我节省一切的cookie。
I need to loop through all the controls in my asp webpage and do something to the control. In one instance I'm making a giant string out of the page and emailing it to myself, and in another case I'm saving everything to a cookie.
问题是masterpages和物品与内部控制它们的集合。我希望能够在一个页面传递给方法,那么有一个方法是通用的,足以遍历最内层的内容页面的所有控件,并与他们合作。我试着用递归这样做,但我的递归是不完整的。
The problem is masterpages and items with collections of controls inside them. I want to be able to pass in a Page to the method, then have that method be generic enough to loop through all controls in the inner-most content page and work with them. I've tried doing this with recursion, but my recursion is incomplete.
欲Page对象传递到的方法,以及在最里面的内容页面通过所有控制该方法循环。我怎样才能做到这一点?
I want to pass a Page object into a method, and have that method loop through all controls in the innermost content page. How can I achieve this?
private static String controlToString(Control control) { StringBuilder result = new StringBuilder(); String controlID = String.Empty; Type type = null; foreach (Control c in control.Controls) { try { controlID = c.ID.ToString(); if (c is IEditableTextControl) { result.Append(controlID + ": " + ((IEditableTextControl)c).Text); result.Append("<br />"); } else if (c is ICheckBoxControl) { result.Append(controlID + ": " + ((ICheckBoxControl)c).Checked); result.Append("<br />"); } else if (c is ListControl) { result.Append(controlID + ": " + ((ListControl)c).SelectedValue); result.Append("<br />"); } else if (c.HasControls()) { result.Append(controlToString(c)); } //result.Append("<br />"); } catch (Exception e) { } } return result.ToString(); }如果没有的try / catch
Without Try/catch
对象引用未设置到对象的实例。
Object reference not set to an instance of an object.
在行控件ID = .....
On line controlID = .....
推荐答案如果你从你的文档的根元素开始你的原来的方法是行不通的:像page.Controls随你便只能通过控制第一级的循环,但要记住一个控制是复合材料。所以,你需要递归实现自己的目标。
Your original method will not work if you start from the root element of your document: something like page.Controls as you will only loop through the first level of controls, but remember a control can be composite. So you need recursion to pull that off.
public void FindTheControls(List<Control> foundSofar, Control parent) { foreach(var c in parent.Controls) { if(c is IControl) //Or whatever that is you checking for { foundSofar.Add(c); if(c.Controls.Count > 0) { this.FindTheControls(foundSofar, c); } } } }更多推荐
通过asp.net网页上的所有控制回路
发布评论