在我的代码后面,我想要设置标签的文本。这是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页面中调用此方法(请参阅我的代码)。我没有收到任何错误消息,但没有看到任何文本!
我在做什么错?
您可以实现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应该从哪一行获得标签?您需要先到达该行,然后获取所需的标签。