效果:datalist显示所有新闻的列表,一个星期以内的新闻后加new字样
前台代码
<div>
<asp:DataList ID="DataList1" runat="server" DataSourceID="SqlDataSource1" Width="450px"
Style="position: relative; top: 9px; float: left;" OnItemCommand="DataList1_ItemCommand" OnItemDataBound="DataList1_ItemDataBound">
<ItemTemplate>
<table style="width: 100%; color: #0C2774; font-size: 13px !important; font-size: 12px;
margin-right: 10px;">
<tr>
<td align="left">
<div style="margin-left: 12px;">
<img src="../image/newsLogimg.png" style="margin-right: 8px;" />
<a class="thumb" href="###" οnclick='window.open("messageDetails.aspx?name=<%#DataBinder.Eval(Container.DataItem,"Title")%>","_blank","width=740,height=690,scrollbars=1,resizable=1,left=20,top=20")'
style="cursor: pointer; text-decoration: none; color: #0C2774; font-size: 12px;">
<asp:Label ID="Label2" runat="server" Style="color: #0C2774;" Text='<%# Eval("Title") %>'></asp:Label>
</a>
<asp:Label id="newImage" Text="new" BackColor= "Red" runat="server" style="margin-right: 8px;" />
</div>
</td>
<td align="right" style="width: 50px;">
<asp:Label ID="Label1" runat="server" Style="color: #868277;" Text='<%# Eval("Time") %>'></asp:Label></td>
</tr>
</table>
</ItemTemplate>
</asp:DataList><asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:StitpDatabaseConnectionString %>"
SelectCommand="SELECT top 8 [Title], convert(varchar(10),[Time],102) as [Time] FROM [Message]">
</asp:SqlDataSource>
</div>
后台代码
protected void DataList1_ItemDataBound(object sender, DataListItemEventArgs e)
{
foreach (DataListItem item in DataList1.Items)
{
Label newImage = (Label)item.FindControl("newImage");
Label TimeLabel = (Label)item.FindControl("Label1");
DateTime newsTime = Convert.ToDateTime(TimeLabel.Text.ToString());
TimeSpan newsTimeSpan = new TimeSpan(newsTime.Ticks);
TimeSpan datetimeNow = new TimeSpan(DateTime.Now.Ticks);
TimeSpan ts = datetimeNow.Subtract(newsTimeSpan);
int days = ts.Days;
if (days <= 7)//一个星期以内提示
{
newImage.Visible = true;
}
else
{
newImage.Visible = false;
}
}
}