[英]Can't find control within asp.net repeater?
I have the following repeater below and I am trying to find lblA in code behind and it fails. 我在下面有以下转发器,我试图在后面的代码中找到lblA并且它失败了。 Below the markup are the attempts I have made:
标记下方是我的尝试:
<asp:Repeater ID="rptDetails" runat="server">
<HeaderTemplate>
<table>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td><strong>A:</strong></td>
<td><asp:Label ID="lblA" runat="server"></asp:Label>
</td>
</tr>
</ItemTemplate>
</asp:Repeater>
</table>
First I tried, 首先我试过,
Label lblA = (Label)rptDetails.FindControl("lblA");
but lblA was null 但是lblA是空的
Then I tried, 然后我试过,
Label lblA = (Label)rptDetails.Items[0].FindControl("lblA");
but Items was 0 even though m repeater contains 1 itemtemplate 但是物品是0,即使m转发器包含1个itemtemplate
You need to set the attribute OnItemDataBound="myFunction"
你需要设置属性
OnItemDataBound="myFunction"
And then in your code do the following 然后在您的代码中执行以下操作
void myFunction(object sender, RepeaterItemEventArgs e)
{
Label lblA = (Label)e.Item.FindControl("lblA");
}
Incidentally you can use this exact same approach for nested repeaters. 顺便提一下,您可以对嵌套转发器使用这种完全相同的方法。 IE:
IE:
<asp:Repeater ID="outerRepeater" runat="server" OnItemDataBound="outerFunction">
<ItemTemplate>
<asp:Repeater ID="innerRepeater" runat="server" OnItemDataBound="innerFunction">
<ItemTemplate><asp:Label ID="myLabel" runat="server" /></ItemTemplate>
</asp:Repeater>
</ItemTemplate>
</asp:Repeater>
And then in your code: 然后在你的代码中:
void outerFunction(object sender, RepeaterItemEventArgs e)
{
Repeater innerRepeater = (Repeater)e.Item.FindControl("innerRepeater");
innerRepeater.DataSource = ... // Some data source
innerRepeater.DataBind();
}
void innerFunction(object sender, RepeaterItemEventArgs e)
{
Label myLabel = (Label)e.Item.FindControl("myLabel");
}
All too often I see people manually binding items on an inner repeater and they don't realize how difficult they're making things for themselves. 我经常看到人们在内部转发器上手动绑定物品,但他们并没有意识到他们为自己制造物品有多困难。
I just had the same problem. 我刚遇到同样的问题。
We are missing the item type while looping in the items. 我们在循环项目时缺少项目类型 。 The very first item in the repeater is the header , and header does not have the asp elements we are looking for.
转发器中的第一个项目是标题 ,标题没有我们正在寻找的asp元素。
Try this: 尝试这个:
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{Label lblA = (Label)rptDetails.Items[0].FindControl("lblA");}
Code for VB.net VB.net的代码
Protected Sub rptDetails_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles rptDetails.ItemDataBound
If e.Item.ItemType = ListItemType.AlternatingItem Or e.Item.ItemType = ListItemType.Item Then
Dim lblA As Label = CType(e.Item.FindControl("lblA"), Label)
lblA.Text = "Found it!"
End If
End Sub
You should bind first. 你应该先绑定。
for example) 例如)
rptDetails.DataSource = dataSet.Tables["Order"];
rptDetails.DataBind();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.