Controling Repeaters
I hate finding controls in repeaters, there is no easy way … it’s sloppy, ugly and prone to errors. Here’s how I’ve done it in the past
Assume:
- Repeater control “rptrMyDocumentComments”
- Control location is within the reapeater header (or footer)
- Header: rptrMyDocumentComments.Controls[0]
- Footer: rptrMyDocumentComments.Controls[rptrMyDocumentCommentsControls.Length-1]
- Misc rows: good luck
Code:
ASPX.CS file
if ((rptrMyDocumentComments != null) && (rptrMyDocumentComments.Controls[0] != null)
&& (rptrMyDocumentComments.Controls[0].FindControl("tbLCMyDocumentNumber") != null)) {
HtmlContainerControl spanMyDocumentNumber =
(HtmlContainerControl)rptrMyDocumentComments.Controls[0].FindControl("tbLCMyDocumentNumber");
spanMyDocumentNumber.InnerHtml += sMyDocumentNumber;
}
In a small bitching session to my mentor (who I'm calling out for not blogging regularly enough recently!) I got told "That's to much work to find a control" and pointed me towards a recursive function by Jeff Atwood who was kind enough to blog about this very problem.
It may mean more code for this one time, but a) cuts out the guessing game and b) is reusable EVERYWHERE you may need to access controls within a repeater (which in my current project is far too often)
Assume:
Code:
ASPX.CS file
HtmlContainerControl spanMyDocumentNumber =
(HtmlContainerControl)MyNamespace.Common.Controls.FindControlRecursive(rptrMyDocumentComments, "tbLCMyDocumentNumber");
if (spanMyDocumentNumber != null) {
spanMyDocumentNumber.InnerHtml += sMyDocumentNumber;
}
MyNamespace.Common file
public static class Controls {
public static Control FindControlRecursive(Control root, String id) {
if (root.ID == id) {
return root;
}
foreach (Control c in root.Controls) {
Control t = FindControlRecursive(c, id);
if (t != null) {
return t;
}
} // foreach control in root
return null;
} // method FindControlRecursive
} // class Controls
Many thanks to
Tim Rayburn for the suggestion, and
Jeff Attwood for being smart enough to come up with the code I'm so delightfully stealing!