C# 从sql表中获取数据,使其看起来像网格
我有以下代码用于从sql表检索数据。 此代码仅检索最后一条记录。 我想显示表中的所有数据C# 从sql表中获取数据,使其看起来像网格,c#,sql,asp.net,sql-server,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(); SqlD
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());
}
}
我想使数据如下图所示。
我应该用桌子吗?!潜水艇?!或者可以使用GridView吗?这里有一种使用asp:Repeater和
aspx:
当前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());
}
}
你可以改变你的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来实现,你能给我举个例子吗?使用DataAdapter而不是DataReader,并放入DataGridView.DataSource=dt。见网页。使用DataTable而不是DataSet。投票关闭太宽-您需要一个显示多行DataGrid、Repeater等的控件,并且需要将其绑定到数据源。您可以使用DataReader或DataSet。关于这两个问题都有很多教程。
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)