如何动态添加标签并将sql数据绑定到标签 [英] how to add label dynamically and bind sql data to label
本文介绍了如何动态添加标签并将sql数据绑定到标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在创建网站,因为我想将sql表中的数据显示到asp.net中的标签中,但是我希望该标签应动态添加并将数据绑定到标签.
如果sql表包含2行,则应添加2个标签并绑定数据
I m creating website in that i want to display data from sql table into label in asp.net.but i want that label should be added dynamically and bind data to label.
if the sql table contains 2 rows the label should be 2 added and bind data
推荐答案
try这一个....
try This one ....
Label lblfirst = new Label();
Label lblsecond = new Label();
lblfirst.Text="bind data from DB";
lblsecond.Text="bind data from DB";
您好,
您可以使用以下代码在表中动态添加尽可能多的标签:
Hi,
You can use following code to add as many labels as rows in your table dynamically:
protected void Page_Load(object sender, EventArgs e)
{
AddDynamicLabels();
}
private void AddDynamicLabels()
{
string ConString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
SqlConnection con = new SqlConnection(ConString);
string CmdString = "Select EmployeeID, FirstName, HireDate FROM Employees ORDER BY Salary DESC";
SqlCommand cmd = new SqlCommand(CmdString, con);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Label lbl = new Label();
lbl.Text = reader["FirstName"].ToString();
lbl.BackColor = System.Drawing.Color.Orange;
lbl.BorderStyle = BorderStyle.Solid;
lbl.BorderWidth = 1;
this.Controls.Add(lbl);
}
con.Close();
}
你好...
考虑标签ID为 LblOne 和SqlDataReader rd1,您可以简单地编写以下代码:
在设计页面中:
Hello ...
Considering the label id as LblOne and SqlDataReader rd1 you can simply code this :
in the design page :
<asp:Label ID="LblOne" runat="server" Text="" />
在后面的代码中:VB.Net代码
in the code behind : VB.Net code
LblOne.Text = String.Empty ' to clear the label
While rd1.read()
LblOne.Text += rd1("firldName").ToString
End While
这篇关于如何动态添加标签并将sql数据绑定到标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文