【问题标题】:How to set the value of a string to all the values of a dropdownlist asp.net如何将字符串的值设置为下拉列表 asp.net 的所有值
【发布时间】:2013-07-08 15:07:32
【问题描述】:

我有一个从数据库填充的下拉列表,当用户单击网页上的添加所有按钮时,我想将字符串“里程碑”的值设置为逗号分隔的字符串,该字符串包含所有值下拉列表。有没有一种简单的方法可以做到这一点?

【问题讨论】:

    标签: c# asp.net


    【解决方案1】:

    使用String.Join:

    string[] ddlValues = ddl.Items.Cast<ListItem>().Select(x => x.Text).ToArray();
    string milestones = string.Join(",", ddlValues));
    

    【讨论】:

      【解决方案2】:

      您可以使用 Linq 选择 DropDownList 的所有项目,使用 String.Join 连接它们:

      string milestoneNames = string.Join(",", 
          ddlMileStone.Items.Cast<ListItem>().Select(i => i.Text));
      

      如果您想要所有值:

      string milestoneValues = string.Join(",", 
          ddlMileStone.Items.Cast<ListItem>().Select(i => i.Value));
      

      【讨论】:

      【解决方案3】:

      这也适用于您。

      string milestones = string.Join(",", ddl.Items.ToArray());
      

      【讨论】:

      • 抱歉没有编译?
      【解决方案4】:
      DropDownList d = new DropDownList();
      d.Items.Add(new ListItem("1", "Foo"));
      d.Items.Add(new ListItem("2", "Bar"));
      string[] items = d.Items.Cast<ListItem>().Select(x => x.Value).ToArray();
      

      【讨论】:

        猜你喜欢
        • 2016-12-21
        • 2020-01-24
        • 2020-04-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-11-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多