Reputation: 3619
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.
Upvotes: 2
Views: 12433
Reputation: 1069
in ASP, write this: -
<asp:DataList ID="dlSample"
runat="server"
OnItemDataBound="dlSample_ItemDataBound">
<ItemTemplate>
<asp:Label ID="lbl" runat="server"
Text='<%# Container.DataItem %>'></asp:Label>
</ItemTemplate>
</asp:DataList>
and in Code Behind write this: -
protected void dlSample_ItemDataBound(object sender, DataListItemEventArgs e)
{
try
{
if (e.Item.DataItem.ToString().Equals("1"))
((Label)e.Item.FindControl("lbl")).Text = "One";
}
catch (Exception ex)
{
throw;
}
}
Upvotes: 2
Reputation: 15663
At the time when dlSample_ItemDataBound
method is called, the expressions in the ItemTemplate
are already evaluated and, even the DataItem is changed, the effect won't be reflected.
You can use the following code block.
<asp:Label ID="lbl" runat="server"
Text='<%# (string)Container.DataItem == "1" ? "one" : (string)Container.DataItem %>'
>
</asp:Label>
You can remove the OnItemDataBound="dlSample_ItemDataBound"
, because won't be used anymore.
As an alternative, if you still want to use this handler:
<asp:DataList ID="dlSample" runat="server" OnItemDataBound="dlSample_ItemDataBound">
<ItemTemplate>
<asp:Label ID="lbl" runat="server"></asp:Label>
</ItemTemplate>
</asp:DataList>
protected void dlSample_ItemDataBound(object sender, DataListItemEventArgs e)
{
//dataitem is supposed to be a string object, so you can cast it to string, no need to call ToString()
var item = (string)e.Item.DataItem;
// find the label with "lbl" ID, use e.Item as the Naming Container
var lbl = (Label)e.Item.FindControl("lbl");
if (item == "1")
lbl.Text = "one";
else
lbl.Text = item;
}
I always prefer the first way to do these things.
Upvotes: 2