【问题标题】:how to set datasource to dropdownlist如何将数据源设置为下拉列表
【发布时间】:2010-11-01 09:18:51
【问题描述】:

我想将数据源添加到下拉列表。此下拉列表是网格视图的列之一。这里我想在不使用 sqldatasource 的情况下,将数据源动态添加到下拉列表中。

(vs2008 和 c#)

【问题讨论】:

    标签: c# gridview drop-down-menu datasource


    【解决方案1】:

    您可以为网格中的下拉列表控件实现 OnDataBinding 事件。如果您可以将 DataSource 属性和其他属性分配给您喜欢的任何内容。将其绑定到 List<YourObject> 偶数。

    在 OnDataBinding 事件上执行此操作还允许您动态自定义 ddl 中的值。因此,如果您需要这种类型的功能,每行的 ddl 可以根据行中的其他一些数据提供一组不同的选项。

    如果使用 OnDataBinding 方法而不是自动(简单模式)连线,则 ASP.NET 控件具有大量灵活性。

    【讨论】:

    • 请告诉我我设置数据源如 OnDataBinding 事件 DropDownList11.DataSource = dataTable; DropDownList11.DataValueField = "项目代码"; DropDownList11.DataTextField = "项目代码"; DropDownList11.DataBind();但是会发生错误,例如当前上下文中不存在名称“DropDownList11”
    【解决方案2】:

    是的,因为它在 itemtemplate 中,所以你不会直接得到它,因为你必须使用 findcontrol

    【讨论】:

      【解决方案3】:

      这是您要查找的代码

      示例 1:

      public enum Color
      {
          RED,
          GREEN,
          BLUE
      }
      

      每个 Enum 类型都派生自 System.Enum。有两种静态方法可帮助将数据绑定到下拉列表控件(并检索值)。它们是 Enum.GetNames 和 Enum.Parse。使用 GetNames,您可以按如下方式绑定到下拉列表控件:

      protected System.Web.UI.WebControls.DropDownList ddColor;
      
      private void Page_Load(object sender, System.EventArgs e)
      {
           if(!IsPostBack)
           {
              ddColor.DataSource = Enum.GetNames(typeof(Color));
              ddColor.DataBind();
           }
      }
      

      示例 2:

      List<Person> myPList = new List<Person>();
      
      
      
      Person p1 = new Person();
      
      p1.ID = 1;
      
      p1.Name = "Bob";
      
      p1.Color = "Blue";
      
      
      
      Person p2 = new Person();
      
      p2.ID = 2;
      
      p2.Name = "Joe";
      
      p2.Color = "Green";
      
      
      
      myPList.Add(p1);
      
      myPList.Add(p2);
      
      
      
      this.DropDownList1.DataSource = myPList;
      
      this.DropDownList1.DataTextField = "Color";
      
      this.DropDownList1.DataValueField = "ID";
      
      this.DropDownList1.DataBind();  
      

      更完整的练习请看这里: https://stackoverflow.com/a/9076237/132239

      也不要忘记将你的答案标记为答案

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-01-24
        • 1970-01-01
        • 2013-10-30
        • 2012-12-15
        • 2021-09-30
        • 1970-01-01
        • 2019-01-07
        • 2011-02-27
        相关资源
        最近更新 更多