2008-11-10 91 views

回答

9

以下是如何在列表頂部添加值的方法。它可以是一個空字符串或一些文本。

<asp:DropDownList ID="categories" runat="server" AppendDataBoundItems="True" AutoPostBack="True" DataSourceID="categoriesDataSource" DataTextField="CategoryName" DataValueField="CategoryID" EnableViewState="False"> 
    <asp:ListItem Value="-1"> 
     -- Choose a Category -- 
    </asp:ListItem>   
</asp:DropDownList> 

一定要設置DropDownList的AppendDataBoundItems = True。

+0

你爲什麼不這項建議添加到您的示例代碼清晰? – Keltex 2008-11-10 16:21:10

0

我提供IEnumerable<string>擴展方法,追加的項目列表的開頭:

public static IEnumerable<string> Prepend(this IEnumerable<string> data, string item) 
    { 
     return new string[] { item == null ? string.Empty : item }.Union(data); 
    } 

及其分類LINQ-Y的,因爲它使用LINQ擴展方法聯盟。它乾淨了一點比這樣做:

var result = new string[]{string.Empty}.Union(from x in data select x.ToString()); 
1

標記:

<asp:DropDownList ID="ddlQualQuestion" runat="server" DataSourceID="sdsQualQuestion" DataTextField="ShortQuestionText" DataValueField="QualificationQuestionKey" AutoPostBack="true" OnSelectedIndexChanged="ddlQualQuestion_SelectedIndexChanged" OnDataBound="ddlQualQuestion_DataBound" />; 

後面的代碼:

protected void ddlQualQuestion_DataBound(object sender, EventArgs e) 
{ 
    ddlQualQuestion.Items.Insert(0, new ListItem("", "0")); 
} 
1

以DOK提供的解決方案:

<asp:DropDownList ID="categories" runat="server" AppendDataBoundItems="True" AutoPostBack="True" DataSourceID="categoriesDataSource" DataTextField="CategoryName" DataValueField="CategoryID" EnableViewState="False"> 
    <asp:ListItem Value="-1"> 
     -- Choose a Category -- 
    </asp:ListItem>   
</asp:DropDownList> 

Addtionally,如果你不想強制用戶做一個選擇,你可以添加一個方法來你的GridView的使用LinqDataSource:

OnSelecting="myGridview_Selecting" 

添加代碼的背後是這樣的:

protected void myGridview_Selecting(object sender, LinqDataSourceSelectEventArgs e) 
{ 
    if (categories.SelectedValue == "-1") 
    { 
     e.WhereParameters.Remove("CategoryID"); 
    } 
}