从数据库中检索前3并放入hhomepage

时间:2018-02-22 19:05:00

标签: asp.net asprepeater

我有一个包含所有最新消息的数据库。我希望主页只显示最新的三个新闻项目。

我的aspx页面设置为:

<div class="row"> 
        <asp:Repeater ID="rptNewsList" runat="server">
        <ItemTemplate>
        <div class="col-md-4"> 
             <h2><%# Eval("Title") %>
                 <small><%# Eval("NewsContent") %></small>
             </h2>           
        </div> 
        <div class="col-md-4">              
              <h2><%# Eval("Title") %>
                 <small><%# Eval("NewsContent") %></small>
             </h2>            
        </div> 
        <div class="col-md-4">              
             <h2><%# Eval("Title") %>
                 <small><%# Eval("NewsContent") %></small>
             </h2>            
        </div>
        </ItemTemplate>
        </asp:Repeater> 
</div>

我的aspx.cs页面设置如下,我正在使用转发器,转发器将相同的消息加载到三列

我希望col 1有最新消息,col 2有最新消息-1和col 3有最新消息-2

protected void Page_Load(object sender, EventArgs e)
    {
        rptNewsList.DataSource = GetNewsList();
        rptNewsList.DataBind();
    }
    private DataTable GetNewsList()
    {
        DataTable dataTable = new DataTable();
        SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["AppConnectionString"].ConnectionString);
        string query = "SELECT top 1 [Id], [Title], [DatePosted], [NewsContent] FROM [News] ORDER BY [Id] DESC";
        connection.Open();
        SqlCommand command = new SqlCommand(query, connection);
        dataTable.Load(command.ExecuteReader());
        connection.Close();
        return dataTable;
    }

我的表格配置如下:

CREATE TABLE [dbo].[News] (
[Id]          INT            IDENTITY (1, 1) NOT NULL,
[Title]       NVARCHAR (100) NOT NULL,
[DatePosted]  DATE           NOT NULL,
[NewsContent] NTEXT          NOT NULL,
[IsRead]      BIT            DEFAULT ((0)) NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);

This is currently being display which is the latest news displayed 3 times

1 个答案:

答案 0 :(得分:0)

我认为您可能需要将查询更改为以下内容:

SELECT DISTINCT TOP 3 [Id], [Title], [DatePosted], [NewsContent] FROM [News] 
ORDER BY [DatePosted] DESC