gpt4 book ai didi

c# - 如何从 SQL 中检索多个值到标签

转载 作者:太空宇宙 更新时间:2023-11-03 12:43:31 24 4
gpt4 key购买 nike

我想从我的 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), 上面的代码会失败,所以一定要进行一些错误处理。

有一些方法可以对此进行优化:

  1. 将所有标签放入一个数组中(确保保持正确的顺序),然​​后您可以执行 titleLabels[i]
  2. 有一个中继器或 GridView ,代表您的实体列表,并定义带有必要标签的模板。然后您可以将数据从您的数据库绑定(bind)到它们,这将导致更漂亮、更易于维护的解决方案,并且更不容易出错。然而,这确实是一个单独的主题,不太适合这个问题,请在线查找教程。

关于c# - 如何从 SQL 中检索多个值到标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38121905/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com