Answers:
如评论中所述,只有在使用DataBound中继器之后,此方法才起作用。
要在标题中找到控件:
lblControl = repeater1.Controls[0].Controls[0].FindControl("lblControl");
在页脚中查找控件:
lblControl = repeater1.Controls[repeater1.Controls.Count - 1].Controls[0].FindControl("lblControl");
public static class RepeaterExtensionMethods
{
public static Control FindControlInHeader(this Repeater repeater, string controlName)
{
return repeater.Controls[0].Controls[0].FindControl(controlName);
}
public static Control FindControlInFooter(this Repeater repeater, string controlName)
{
return repeater.Controls[repeater.Controls.Count - 1].Controls[0].FindControl(controlName);
}
}
更好的解决方案
您可以在ItemCreated事件中检查项目类型:
protected void rptSummary_ItemCreated(Object sender, RepeaterItemEventArgs e) {
if (e.Item.ItemType == ListItemType.Footer) {
e.Item.FindControl(ctrl);
}
if (e.Item.ItemType == ListItemType.Header) {
e.Item.FindControl(ctrl);
}
}
在Repeater(页眉,项目,页脚)中找到控件
public static class FindControlInRepeater
{
public static Control FindControl(this Repeater repeater, string controlName)
{
for (int i = 0; i < repeater.Controls.Count; i++)
if (repeater.Controls[i].Controls[0].FindControl(controlName) != null)
return repeater.Controls[i].Controls[0].FindControl(controlName);
return null;
}
}
这在VB.NET中,如果需要,只需将其转换为C#:
<Extension()>
Public Function FindControlInRepeaterHeader(Of T As Control)(obj As Repeater, ControlName As String) As T
Dim ctrl As T = TryCast((From item As RepeaterItem In obj.Controls
Where item.ItemType = ListItemType.Header).SingleOrDefault.FindControl(ControlName),T)
Return ctrl
End Function
并易于使用:
Dim txt as string = rptrComentarios.FindControlInRepeaterHeader(Of Label)("lblVerTodosComentarios").Text
尝试使其与页脚一起使用,项目控件也=)
最好的干净方法是在Item_Created事件中:
protected void rptSummary_ItemCreated(Object sender, RepeaterItemEventArgs e)
{
switch (e.Item.ItemType)
{
case ListItemType.AlternatingItem:
break;
case ListItemType.EditItem:
break;
case ListItemType.Footer:
e.Item.FindControl(ctrl);
break;
case ListItemType.Header:
break;
case ListItemType.Item:
break;
case ListItemType.Pager:
break;
case ListItemType.SelectedItem:
break;
case ListItemType.Separator:
break;
default:
break;
}
}
private T GetHeaderControl<T>(Repeater rp, string id) where T : Control
{
T returnValue = null;
if (rp != null && !String.IsNullOrWhiteSpace(id))
{
returnValue = rp.Controls.Cast<RepeaterItem>().Where(i => i.ItemType == ListItemType.Header).Select(h => h.FindControl(id) as T).Where(c => c != null).FirstOrDefault();
}
return returnValue;
}
查找并强制转换控件。(基于Piyey的VB答案)
对于ItemDataBound
protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Header)//header
{
Control ctrl = e.Item.FindControl("ctrlID");
}
else if (e.Item.ItemType == ListItemType.Footer)//footer
{
Control ctrl = e.Item.FindControl("ctrlID");
}
}