Code Behind (C#):
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (!Page.IsPostBack)
{
List<string> lst = new List<string>();
lst.Add("1");
lst.Add("2");
dlSample.DataSource = lst;
dlSample.DataBind();
}
}
catch (Exception ex)
{
throw;
}
}
protected void dlSample_ItemDataBound(object sender, DataListItemEventArgs e)
{
try
{
if (e.Item.DataItem.ToString().Equals("1"))
e.Item.DataItem = "one";
}
catch (Exception ex)
{
throw;
}
}
ASP:
<asp:DataList ID="dlSample" runat="server" OnItemDataBound="dlSample_ItemDataBound">
<ItemTemplate>
<asp:Label ID="lbl" runat="server" Text='<%# Eval("") %>'></asp:Label>
</ItemTemplate>
</asp:DataList>
I have used List on my code and inserting items on it. After that I have binded it programmatically and on my ItemDataBound event I have modified an item at run-time. I have problem on displaying the items on the DataList control. My question is how would I display it using the Eval data-binding expression on my ASP or is there any approach aside on Eval?
Thank you very much in advance.
At the time when
dlSample_ItemDataBoundmethod is called, the expressions in theItemTemplateare already evaluated and, even the DataItem is changed, the effect won’t be reflected.You can use the following code block.
You can remove the
OnItemDataBound="dlSample_ItemDataBound", because won’t be used anymore.As an alternative, if you still want to use this handler:
I always prefer the first way to do these things.