我想从我的SQL数据库中将多个值检索到单个aspx页面上的多个标签。现在正在发生的事情是,我已经成功地从第一行中检索了值,但是当涉及到第二行以及之后时,它将继续从第一行中重复这些值。
这是我用来从数据库中选择值的代码。谁能帮我解决这个问题,同时检索其他行?
页面后面的代码:
public partial class filmes : System.Web.UI.Page
{
string strConnString = ConfigurationManager.ConnectionStrings["ENTDB"].ConnectionString;
string str;
SqlCommand com;
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(strConnString);
con.Open();
str = "select * from FilmesSeries order by IDFilmesSeries desc";
com = new SqlCommand(str, con);
SqlDataReader reader = com.ExecuteReader();
int ID=1;
while (reader.Read())
{
ID++;
Label tituloControl= (Label) Page.FindControl("Titulo"+ID);
if(tituloControl!=null)
{
tituloControl.ID=" Titulo"+ID;
tituloControl.Text= reader["Titulo"].ToString();
}
Label GeneroControl= (Label) Page.FindControl("Genero"+ID);
if(GeneroControl!=null)
{
GeneroControl.ID=" Genero"+ID;
GeneroControl.Text= reader["NomeGenero"].ToString();
}
}
reader.Close();
con.Close();
}
}
filmes.aspx页面:
<div class="row">
<div class="col-md-5">
<asp:Label id="Titulo1" runat="server" />
<asp:Label id="Genero1" runat="server" />
</div>
</div>
<hr>
<div class="row">
<div class="col-md-5">
<asp:Label id="Titulo2" runat="server" />
<asp:Label id="Genero2" runat="server" />
</div>
</div>
最佳答案
首先,您需要获取正确的控件索引以分配给:
int i = 1;
while (reader.Read())
{
...
i++;
}
然后,您需要从页面中检索这些控件:
int i = 1;
while (reader.Read())
{
Label titleLabel = (Label)this.FindControl("Titulo" + i);
Label genreLabel = (Label)this.FindControl("NomeGenero" + i);
...
i++;
}
最后分配
int i = 1;
while (reader.Read())
{
Label titleLabel = (Label)this.FindControl("Titulo" + i);
Label genreLabel = (Label)this.FindControl("NomeGenero" + i);
titleLabel.Text = reader["Titulo"].ToString();
genreLabel.Text = reader["NomeGenero"].ToString();
i++;
}
但是请注意,如果您说数据库中有10个项目,并且页面上只有9对标签(即
Titulo9
是最后一个,没有Titulo10
),则上面的代码将失败,因此请确保这样做一些错误处理。有一些方法可以对此进行优化:
将所有标签放入数组(确保保持正确的顺序),然后可以执行
titleLabels[i]
有一个中继器或一个gridview,它代表您的实体列表,并定义带有必要标签的模板。然后,您可以从数据库中将数据绑定到它们,这将导致更漂亮,更易于维护的解决方案,并且不易出错。但是,这实际上是一个单独的主题,不太适合这个问题,请在线查找教程。
关于c# - 如何从SQL检索多个值到标签,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38121905/