2009-09-21 109 views
2

我正在使用ASP.NET動態數據。在Insert.aspx頁面中,我有幾個下拉列表可供選擇。下拉列表中的字段是數據庫中的必填字段。因此,下拉式廣告不會在下拉菜單中顯示「選擇」作爲默認選項。我想在下拉列表中顯示的數據庫的其他記錄頂部添加「選擇」選項。請注意,字段不是必填字段,因此默認情況下,「選擇」選項不會顯示在那裏。我怎樣才能做到這一點?在DropDown中添加「選擇」項

回答

8

用插入法結合的dropdownlists後添加您的「選擇」項:

myDropDownList.DataBind(); 
// To make it the first element at the list, use 0 index : 
myDropDownList.Items.Insert(0, new ListItem("Select", string.Empty)); 
+0

謝謝!有效... – 2009-09-21 11:14:22

1

我會爲必選下拉字段的自定義FieldTemplate。在控件的OnDataBinding事件中插入「選擇」項。我還會有一個客戶端RequiredFieldValidator來確保選擇「Select」以外的內容,然後才能回發。

<%@ 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會在默認使用。

1

在索引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(); 
    } 
} 
0
//---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; 
    } 
0

選擇頂層1 '0' 作爲valueField, '請選擇 - ' 作爲文本字段從dummtable UNION 選擇ID,文本從yourTable

從後端控制給予更多的靈活性