【问题标题】:How to add option "Any" in a dropdownlist when data is filled from database?从数据库填充数据时,如何在下拉列表中添加选项“任何”?
【发布时间】:2013-07-16 01:28:42
【问题描述】:

我有下拉列表,其中通过连接到数据库来添加值。

这是我的代码:

<asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="SqlDataSource1" DataTextField="devicetype" DataValueField="devicetype"></asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:PHSNew %>" SelectCommand="SELECT DISTINCT [devicetype] FROM [dx_devices]"></asp:SqlDataSource>

现在我想在下拉列表中再添加一个选项“Any”。

如何添加?

【问题讨论】:

    标签: c# asp.net sql-server drop-down-menu


    【解决方案1】:

    应该这样做:

    ddl_MyItems.Items.Insert(0, new ListItem("--Any--", String.Empty));
    ddl_MyItems.SelectedIndex = 0;
    

    【讨论】:

      【解决方案2】:

      在您的DropDownList 中,您需要添加AppendDataBoundItems="true" 以允许这样做,您的DropDownList 将类似于:

      <asp:DropDownList ID="DropDownList1" runat="server" AppendDataBoundItems="true" DataSourceID="SqlDataSource1" 
      DataTextField="devicetype" DataValueField="devicetype">
      
      <asp:ListItem Text="Any" Value="0"></asp:ListItem>
      
      </asp:DropDownList>
      

      【讨论】:

      • 这将在下拉列表的开头添加项目,这是大多数有类似问题的编码人员不想要的。
      【解决方案3】:

      不是在 .aspx 页面上添加数据源,而是在代码隐藏的数据集中获取 sql 查询的结果,然后手动将数据集中的所有项目添加到下拉列表中,并在末尾添加“任何”项目你的下拉列表。

      编辑

      替代方法:

      将属性OnDataBound="DropDownList1_DataBound" 添加到您现有的下拉列表中。

      <asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="SqlDataSource1" DataTextField="devicetype" DataValueField="devicetype" OnDataBound="DropDownList1_DataBound"></asp:DropDownList>
      

      将以下代码添加到您的代码隐藏中。在绑定您在 .aspx 页面上指定的数据源后,这将在下拉列表的末尾添加 Any 项。

      VB

      Protected Sub DropDownList1_DataBound(sender As Object, e As EventArgs)
              Dim ite As New ListItem
              ite.Text = "any"
              DropDownList1.Items.Add(ite)
      End Sub
      

      C#

      protected void DropDownList1_DataBound(object sender, EventArgs e)
      {
          ListItem ite = new ListItem();
          ite.Text = "any";
          DropDownList1.Items.Add(ite);
      }
      

      【讨论】:

      • 我确实拒绝了 "AppendDataBoundItems="true" 和 谢谢你:)
      猜你喜欢
      • 1970-01-01
      • 2021-01-05
      • 2010-09-17
      • 2019-02-23
      • 1970-01-01
      • 2014-12-25
      相关资源
      最近更新 更多