Reputation: 113
Actually i'm developing a web template with asp.net using c# and my connection string is:
<connectionStrings>
<add name="NorthwindConnectionString"
connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\SecurityTutorials.mdf;Integrated Security=True;User Instance=True"
providerName="System.Data.SqlClient"/>
</connectionStrings>
and by using below code from code behind i have connected to the data base:
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();
}
}
I'm using listview, and i want to access the data from the data base before to bind the data by ListView1.DataBind(); and reformat the data and set it as label.text inside the listview. currently i'm using below code to show the label data:
<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>
but i want to delete the <%# Eval("ProductID") %> and the other two as well and set the label.text from code behind. appreciate your consideration.
Upvotes: 0
Views: 5787
Reputation: 432
Use the following event handler in code behind:
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
}
}
Connect this event handler to your listview:
<asp:ListView ID="ListView1" runat="server" OnItemDataBound="MyListView_ItemDataBound" />
Upvotes: 3
Reputation: 42669
ListView has ItemDataBind event which gets called everytime a records gets datebound to the ListView template. Create an even handler and within it
Use the e.Item.DataItem property to get the reference of object being bound, and then go ahead and do the formatting as you required.
Upvotes: 0