隐藏代码(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>
我在代码中使用了 List 并在其中插入了项目。之后,我以编程方式绑定(bind)它,并在 ItemDataBound 事件上我在运行时修改了一个项目。我在显示 DataList 控件上的项目时遇到问题。我的问题是如何使用 ASP 上的 Eval 数据绑定(bind)表达式来显示它,或者 Eval 上还有其他方法吗?
提前非常感谢您。
最佳答案
在调用dlSample_ItemDataBound
方法时,ItemTemplate
中的表达式已经被求值,即使DataItem发生变化,效果也不会反射(reflect)出来。
您可以使用以下代码块。
<asp:Label ID="lbl" runat="server"
Text='<%# (string)Container.DataItem == "1" ? "one" : (string)Container.DataItem %>'
>
</asp:Label>
您可以删除OnItemDataBound="dlSample_ItemDataBound"
,因为将不再使用。
作为替代方案,如果您仍想使用此处理程序:
<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;
}
我总是更喜欢第一种方式来做这些事情。
关于c# - 使用 asp 服务器控件 DataList 时,如何将 Eval 数据绑定(bind)表达式绑定(bind)到 Label?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9714547/