2011-11-09 29 views
0

其實我使用C#開發具有asp.net網頁模板,我的連接字符串是:使用下面的代碼如何從代碼中設置標籤文本中的ListView背後

<connectionStrings> 
<add name="NorthwindConnectionString" 
connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\SecurityTutorials.mdf;Integrated Security=True;User Instance=True" 
providerName="System.Data.SqlClient"/> 
</connectionStrings> 

,並從後面的代碼我有連接到所述數據的基礎上:

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(); 

     } 
    } 

我使用列表視圖,並且我要訪問從之前的數據基礎的數據綁定由ListView1.DataBind數據();並重新格式化數據並將其設置爲listview中的label.text。目前我使用下面的代碼來顯示標籤數據:

<td> 
    <asp:Label ID="lblProdID" runat="server" 
     Text='<%# Eval("ProductID") %>' /> 
</td> 
<td> 
    <asp:Label ID="lblProdName" runat="server" 
     Text="<%# Eval("ProductName") %>" /> 
</td> 
<td> 
    <asp:Label ID="cbDiscontinued" runat="server" 
     Text='<%# Eval("Discontinued") %>' /> 
</td> 

,但我想刪除<%#的eval(「產品ID」)%>,其他兩個也和設置從label.text後面的代碼。 感謝您的考慮。

回答

3

使用在以下代碼的事件處理程序的背後:

<asp:ListView ID="ListView1" runat="server" OnItemDataBound="MyListView_ItemDataBound" /> 

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連接

0

ListView有ItemDataBind事件,每當記錄獲取日期綁定到ListView模板時被調用。創建一個處理程序,並在其中創建一個處理程序

使用e.Item.DataItem屬性獲取被綁定對象的引用,然後繼續並根據需要執行格式設置。

相關問題