实际上我正在使用c#开发一个带有asp.net的web模板,我的连接字符串是:
<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();
}
}
我正在使用listview,我想在通过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>
但我想删除&lt;%#Eval(“ProductID”)%&gt;另外两个也从后面的代码中设置label.text。 感谢您的考虑。
答案 0 :(得分:3)
在后面的代码中使用以下事件处理程序:
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
}
}
将此事件处理程序连接到列表视图:
<asp:ListView ID="ListView1" runat="server" OnItemDataBound="MyListView_ItemDataBound" />
答案 1 :(得分:0)
ListView有ItemDataBind事件,每次记录获取ListView模板的日期时都会调用该事件。在其中创建一个偶数处理程序
使用e.Item.DataItem属性获取被绑定对象的引用,然后继续并根据需要进行格式化。