需要使用 C# FindControl 的帮助
我的面板内有一个中继器。
在这个中继器内,我有另一个面板。在某些条件下,我想设置此 panel.visibility = false
。
在后面的代码中,我尝试在 OnItemDataBound
上找到面板并设置visible=false。但它只返回未设置到对象实例的对象引用。
。我猜这是因为它找不到面板。
这是我的代码:
<asp:Panel ID="Panel1" runat="server">
<asp:Repeater ID="Repeater1" runat="server" OnItemDataBound="repComments_OnDataBound">
<ItemTemplate>
<div>
<asp:Panel runat="server" ID="commentAdminPanel" CssClass="floatRight" >
<img id='deleteComment' class='deleteComment' src='/img/delete1.jpg' />
</asp:Panel>
</div>
</div>
</ItemTemplate>
</asp:Repeater>
</asp:Panel>
这是我背后的代码:
protected void repComments_OnDataBound(Object sender, RepeaterItemEventArgs e)
{
Panel panel = (Panel)Repeater1.FindControl("commentAdminPanel");
panel.Visible = false;
}
我做错了什么?
I have a repeater inside a panel.
Inside this repeater I have another panel.Upon certain conditions, I want to set this panel.visibility = false
.
In the code behind, I try locating the panels on OnItemDataBound
and set visible=false. But it only returns Object reference not set to an instance of an object.
. I guesing it's because it can't locate the panel.
Here is my code:
<asp:Panel ID="Panel1" runat="server">
<asp:Repeater ID="Repeater1" runat="server" OnItemDataBound="repComments_OnDataBound">
<ItemTemplate>
<div>
<asp:Panel runat="server" ID="commentAdminPanel" CssClass="floatRight" >
<img id='deleteComment' class='deleteComment' src='/img/delete1.jpg' />
</asp:Panel>
</div>
</div>
</ItemTemplate>
</asp:Repeater>
</asp:Panel>
And here is my code behind:
protected void repComments_OnDataBound(Object sender, RepeaterItemEventArgs e)
{
Panel panel = (Panel)Repeater1.FindControl("commentAdminPanel");
panel.Visible = false;
}
What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一个问题是您直接调用转发器,而不是绑定项模板 -
e.Item.FindControl
而不是Repeater1.FindControl
。另一个问题是
ItemDataBound
事件也会针对页眉和页脚触发,并且您没有检查列表项的类型 (ListItemType 枚举)您位于转发器中。由于您没有标题项(这将是调用处理程序的第一个项),因此没有面板控件并且转换失败。
您只需要
Item
和AlternatingItem
项目类型:One issue is that you are calling the repeater directly, instead of the bound item template -
e.Item.FindControl
instead ofRepeater1.FindControl
.The other issue is that the
ItemDataBound
event will also fire for header and footer, and you are not checking the type of list item (ListItemType enum) you are on in the repeater.Since you don't have a header item (which would be the first item to call the handler), there is no panel control and the cast fails.
You only need the
Item
andAlternatingItem
item types: