代码之家  ›  专栏  ›  技术社区  ›  Manoj Attal

在下拉列表中添加“选择”项

  •  2
  • Manoj Attal  · 技术社区  · 15 年前

    我正在使用ASP.NET动态数据。在Insert.aspx页面中,我有几个下拉列表要选择。下拉列表表示的字段是数据库中的必填字段。因此,下拉列表不会在下拉列表中显示“选择”作为默认选项。我想在下拉列表中显示的数据库中的其他记录顶部添加“选择”选项。请注意,该字段不是必填字段,因此默认情况下,动态数据不会显示“选择”选项。我怎样才能做到这一点?

    5 回复  |  直到 15 年前
        1
  •  9
  •   Canavar    15 年前

    使用插入方法绑定DropDownList后添加“选择”项:

    myDropDownList.DataBind();
    // To make it the first element at the list, use 0 index : 
    myDropDownList.Items.Insert(0, new ListItem("Select", string.Empty));
    
        2
  •  1
  •   Aaron Hoffman    15 年前

    <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="ForeignKeyRequired_Edit.ascx.cs"
     Inherits="DDWANorthwind.DynamicData.FieldTemplates.ForeignKeyRequired_Edit" %>
    <asp:DropDownList ID="DropDownList1" runat="server" CssClass="droplist">
    </asp:DropDownList>
    <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" 
     ControlToValidate="DropDownList1" ErrorMessage="Selection Required"></asp:RequiredFieldValidator>
    

    -

      protected override void OnDataBinding(EventArgs e)
      {
       base.OnDataBinding(e);
    
       if (Mode == DataBoundControlMode.Edit)
       {
        string foreignkey = ForeignKeyColumn.GetForeignKeyString(Row);
        ListItem item = DropDownList1.Items.FindByValue(foreignkey);
        if (item != null)
        {
         DropDownList1.SelectedValue = foreignkey;
        }
       }
       else if (Mode == DataBoundControlMode.Insert &&
        Column.IsRequired)
       {
        DropDownList1.Items.Insert(0, new ListItem("Select", ""));
       }
      }
    

    您必须使用UIHint属性,以便在默认情况下使用此FieldTemplate。

        3
  •  1
  •   Cylon Cat    15 年前

    在索引0处添加一个顶级元素效果很好,但LINQ提供了另一种可能性,即返回“select”或“pick something”或“all”作为数据的一部分。已将下拉列表数据绑定到此函数:

    public static List<string> GetRegions()
    {
        using (NorthwindDataContext nw = new NorthwindDataContext())
        {
            IQueryable<string> regionQuery = nw.Customers
                .Where(c => c.Region != null)
                .OrderBy(c => c.Region)
                .Select(c => c.Region)
                .Distinct();
            return (new List<string>() { "All" }).Concat(regionQuery).ToList();
        }
    }
    
        4
  •  0
  •   Mostafa Maoui    8 年前
     //---Populate Category DropDownList
        private void getData()
        {
    
            var category = (from c in CoffeeContext.tblProductTypes
                            select new { c.ProductType, c.Description }).ToList();
            cbxCategory.DataTextField = "Description";
            cbxCategory.DataValueField = "ProductType";
            cbxCategory.DataSource = category;
            cbxCategory.DataBind();
            cbxCategory.Items.Insert(0, "--Select Type--");
            cbxCategory.SelectedIndex = 0;
        }
    
        5
  •  0
  •   Monkey D. luffy    7 年前

    协会 从表格中选择ID、文本

    来自后端的控件提供了更大的灵活性