我有以下代码用于从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());
}
}
我应该使用桌子吗?! div的?或者是否可以使用GridViews?
答案 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中完成