c# - 使用 asp 服务器控件 DataList 时,如何将 Eval 数据绑定(bind)表达式绑定(bind)到 Label?

标签 c# asp.net web

隐藏代码(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/

相关文章:

c# - 处置 StringBuilder 对象

c# - ExecuteStoreQuery 将参数传递给 SQL 语句

c# - 页面类提供了哪些响应方法?

css - 如何通过 CSS 设置输入字段的最大整数值?

c# - c#中两位小数的数字分组

c# - 通过 ICustomTypeDescriptor 生成 WPF DataGrid AutoColumn

c# - 如何在asp.net Web应用程序的代码背后使用jquery

asp.net - 如何使用 C# 在自定义验证器中包含正则表达式

python - Flask 将 PDF 作为自己的页面处理

web - 检查命令与来自其他聚合的数据的有效性