【问题标题】:DataBind of DropDownList works, but does not show in code behindDropDownList 的 DataBind 有效,但未显示在后面的代码中
【发布时间】:2011-03-17 18:48:04
【问题描述】:

我正在处理定义了 ASP DropDownList 的网页,并且在页面加载时,数据源通过 DataSource.DataBind() 绑定到它。当我单步执行代码时,下拉列表中没有显示任何内容,但是当页面实际显示时,列表中确实有项目。 DataBind() 究竟什么时候被应用到控件上?

问题是 SQL 后端返回的某些值的文本为空,因此该行的下拉列表中没有显示任何内容。我只想将值用作文本,但前提是文本为空。当我将代码循环并在 DataBind() 之后立即执行此操作时,代码中的下拉列表中没有任何内容。

谢谢!

【问题讨论】:

    标签: asp.net data-binding drop-down-menu pageload


    【解决方案1】:

    您的具体示例的最佳选择是按照 kd7 所说的去做,并修改您的查询。但是,如果您需要对项目进行其他修改,您可以在 DropDownList 的 DataBound 事件中访问它们。 MSDN。此事件在绑定发生后触发。

    【讨论】:

    • 谢谢,这就是我想要的。效果很好!我想这样做的原因是,对于所有项目/价值组合,在未来掌握所有可能性会非常复杂。我知道这并不完美,但我宁愿这样做,也不愿花几天时间深入一个我对涵盖所有内容知之甚少的大型数据库。
    【解决方案2】:

    你可以

    a) 修改您的数据库查询以排除空值

    b) 在数据绑定之前,遍历返回的数据并删除不需要的值。

    【讨论】:

      【解决方案3】:

      您可以在分配数据之前对数据使用 LINQ,以便动态创建一个新类型,并按照您的需要安排数据。这是一个简单的例子:

      // This simulates the data you get from the DB
      List<SomeObject> lstData = new List<SomeObject>();
      lstData.Add(new SomeObject() { ID = "1", Text = "One" });
      lstData.Add(new SomeObject() { ID = "2", Text = "" });
      lstData.Add(new SomeObject() { ID = "3", Text = "Three" });
      
      // This will take your data and create a new version of it substituting the
      // ID field into the Text field when the Text is null or empty.
      yourDropDownList.DataSource = lstData.Select(i => new {
               ID = i.ID,
               Text = string.IsNullOrEmpty(i.Text) ? i.ID : i.Text }).ToList();
      
      // Then just databind
      yourDropDownList.DataBind();
      

      DropDownList 将包含以下项目:

      One
      2
      Three
      

      【讨论】:

        猜你喜欢
        • 2018-12-16
        • 2011-10-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-01-12
        • 1970-01-01
        • 2012-03-06
        相关资源
        最近更新 更多