如何在代码后面的listview中设置标签文本

实际上我正在使用c#开发一个带有asp.net的web模板,我的连接字符串是:

   

并通过使用代码后面的代码,我连接到数据库:

 using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\SecurityTutorials.mdf;Integrated Security=True;User Instance=True")) { conn.Open(); using (System.Data.SqlClient.SqlDataAdapter dad = new System.Data.SqlClient.SqlDataAdapter("SELECT [ProductID], [ProductName], [Discontinued] FROM [Alphabetical list of products]", conn)) { System.Data.DataTable test = new System.Data.DataTable(); dad.Fill(test); ListView1.DataSource = test; ListView1.DataBind(); } } 

我正在使用listview,我想在通过ListView1.DataBind()绑定数据之前从数据库访问数据; 并重新格式化数据并将其设置为listview中的label.text。 目前我正在使用下面的代码来显示标签数据:

  <asp:Label ID="lblProdID" runat="server" Text='' />   <asp:Label ID="lblProdName" runat="server" Text="" />   <asp:Label ID="cbDiscontinued" runat="server" Text='' />  

但我想删除和其他两个,并从后面的代码中设置label.text。 感谢您的考虑。

在后面的代码中使用以下事件处理程序:

 protected void ListView1_ItemDataBound(object sender, ListViewItemEventArgs e) { if (e.Item.ItemType == ListViewItemType.DataItem) { // Display the e-mail address in italics. Label lblProdID = (Label)e.Item.FindControl("lblProdID"); // Here, lblProdID contains your data ProductID as text, change to "My Text" lblProdID.Text = "My Text"; DataRowView rowView = e.Item.DataItem as DataRowView; string myProductID = rowView["ProductID"].ToString(); // Here, you can access your data } } 

将此事件处理程序连接到列表视图:

  

ListView具有ItemDataBind事件,每当记录获得ListView模板的日期绑定时,就会调用该事件。 在其中创建一个偶数处理程序

使用e.Item.DataItem属性获取绑定对象的引用,然后继续并根据需要进行格式化。