我想访问ListView中的按钮btn3
。 ListView本身位于Repeater的ItemTemplate中。
<asp:Repeater runat="server" ID="rep1">
<ItemTemplate>
<asp:ListView ID="ListView1" runat="server" DataSourceID="SqlDataSource1">
...
<asp:Button ID="btn3" runat="server" Text='<%#Eval("likes").ToString()%>'/>
...
</asp:ListView>
</ItemTemplate>
</asp:Repeater>
当我尝试在Repeater的btn3
事件中访问ItemDataBound
时,返回的值为null:
protected void repeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
Button btn1 = (Button)e.Item.FindControl("Btn3"); // btn1 is null
}
}
答案 0 :(得分:0)
您可以设置ListView的ItemDataBound
事件处理程序:
<asp:Repeater runat="server" ID="rep1">
<ItemTemplate>
<asp:ListView ID="ListView1" runat="server" OnItemDataBound="ListView1_ItemDataBound" DataSourceID="SqlDataSource1">
...
</asp:ListView>
</ItemTemplate>
</asp:Repeater>
并在代码隐藏中检索按钮:
protected void ListView1_ItemDataBound(object sender, ListViewItemEventArgs e)
{
if (e.Item.ItemType == ListViewItemType.DataItem)
{
Button btn3 = e.Item.FindControl("btn3") as Button;
...
}
}
<小时/> 如果您想在Repeater
ItemDataBound
事件处理程序中执行此操作(但我不确定此时是否填充了ListView):
protected void repeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
ListView ListView1 = e.Item.FindControl("ListView1") as ListView;
List<Button> buttons = new List<Button>();
foreach (ListViewItem lvItem in ListView1.Items)
{
buttons.Add(lvItem.FindControl("Btn3") as Button);
}
// Use the list of buttons
...
}
}