在我的代码隐藏中,我希望设置标签的文本。这是aspx代码:
<asp:ListView ID="lstRegistrations" runat="server">
<LayoutTemplate>
<table cellspacing="0" cellpadding="0" border="0">
<tr>
<th width="80" align="left">
<asp:Label ID="lblDate" runat="server" Text="<%= GetTranslatedText(7726) %>" />
</th>
<th width="150" align="left">
<asp:Label ID="lblAuthor" runat="server" Text="<%= GetTranslatedText(7728) %>" />
</th>
<th width="290" align="left">
<asp:Label ID="lblRegistration" runat="server" Text="<%= GetTranslatedText(6671) %>" />
</th>
<th width="60" align="left">
<asp:Label ID="lblVersion" runat="server" Text="<%= GetTranslatedText(13) %>" />
</th>
</tr>
<tr>
<td colspan="4" style="height: 3px;"></td>
</tr>
<tr runat="server" id="itemPlaceholder"></tr>
</table>
</LayoutTemplate>
<ItemTemplate>
<tr style="background-color:#FFFFD0;">
<td style="padding-left: 3px">
<%# ((DateTime)Eval("Date")).ToString("d-M-yyyy") %>
</td>
<td>
<%# GetStaffNameById((int)Eval("StaffID")) %>
</td>
<td>
<%# Server.HtmlEncode(Eval("Text").ToString())%>
</td>
<td>
<%# Eval("Version") %>
</td>
</tr>
</ItemTemplate>
<AlternatingItemTemplate>
<tr style="background-color: #C89292">
<td style="padding-left: 3px">
<%# ((DateTime)Eval("Date")).ToString("d-M-yyyy") %>
</td>
<td>
<%# GetStaffNameById((int)Eval("StaffID")) %>
</td>
<td>
<%# Server.HtmlEncode( Eval("Text").ToString() )%>
</td>
<td>
<%# Eval("Version") %>
</td>
</tr>
</AlternatingItemTemplate>
</asp:ListView>
在顶部,在layoutTemplate中我有4个标签,我想要更改文本属性。我试图使用lstRegistrations.FindControl()方法访问标签,但此方法找不到标签。我也尝试过Page.FindControl()方法,但是这个方法要么找不到标签。然后我想,我创建了一个方法并在我的aspx页面中调用它(参见我的代码)。我没有得到任何错误,但我没有看到任何文字!
我做错了什么?
答案 0 :(得分:3)
您想如何指定标签的值?什么时候装?当用户选择某个动作时?
您可以实现ItemDataBound事件,并为每一行访问标签以设置其文本...
protected void ListView_ItemDataBound(object sender, ListViewItemEventArgs e)
{
if (e.Item.ItemType == ListViewItemType.DataItem)
{
Label someLabel = (Label)e.Item.FindControl("MyLabel");
someLabel.Text = "Hurray!";
}
}
您的FindControl()永远不会工作,因为每行都有一组标签。表单FindControl应该获取标签的哪一行?您需要先到达行,然后获取所需的标签。
答案 1 :(得分:0)
你可以:
问题是,在ListView上调用DataBind()之前,LayoutTemplate中的项目不可用。因此,FindControl在此之前返回null。