从sql表中获取数据看起来像网格

时间:2015-10-26 13:22:18

标签: c# sql asp.net sql-server

我有以下代码用于从sql表中检索数据。 此代码仅检索最后一条记录。 我想显示表格中的所有数据。

using (SqlConnection con = new SqlConnection(CS))
        {
            SqlCommand cmd = new SqlCommand("select auction_number, auction_title from Auctions", con);
            con.Open();

            SqlDataReader myReader = cmd.ExecuteReader();
            while (myReader.Read())
            {
                Label1.Text = (myReader["auction_number"].ToString());
                Label2.Text = (myReader["auction_title"].ToString());
            }
        }

我想让数据看起来如下图所示。 enter image description here

我应该使用桌子吗?! div的?或者是否可以使用GridViews?

2 个答案:

答案 0 :(得分:0)

这是asp:Repeater结合<div>

的一种方法

ASPX:

<asp:Repeater ID="Repeater1" runat="server" DataSourceID="edsList">  
<ItemTemplate>
<div>
 <asp:Label ID="Label1" runat="server" Text='<%#Eval("auction_number") %>'></asp:Label>
 <asp:Label ID="Label2" runat="server" Text='<%#Eval("auction_title") %>'></asp:Label>
 </div>
</ItemTemplate>
</asp:Repeater>

CS:

string query = "select auction_number, auction_title from Auctions";
using (SqlConnection myConnection = new SqlConnection(ConnectionString))
{
    using (SqlCommand cmd = new SqlCommand(query, myConnection))
    {
        myConnection.Open();
        SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
        DataTable dt = new DataTable();
        dt.Load(dr);

        Repeater1.DataSource = dt;
        Repeater1.DataBind();
    }
}

答案 1 :(得分:0)

您当前的SQL为表中的每一行选择两个字段。

您可以更改C#以将其显示为3对,就像Barlet的答案一样。

或者您可以更改SQL以返回您想要的“形状”数据。这是怎么做的:

 select max(case when rn % 3 = 0 then auction_number else 0 end) as an1,
        max(case when rn % 3 = 0 then auction_title else '' end) as at1,
        max(case when rn % 3 = 1 then auction_number else 0 end) as an2,
        max(case when rn % 3 = 1 then auction_title else '' end) as at2,
        max(case when rn % 3 = 2 then auction_number else 0 end) as an3,
        max(case when rn % 3 = 2 then auction_title else '' end) as at3
 from (select auction_number, auction_title, ROW_NUMBER() OVER () AS rn
       from Auctions) sub
 group by trunc(rn / 3) 

可能在C#中做得更好 - 但可以在SQL中完成