2009-06-11 41 views
29

在我的頁面上,我有一個DropDownList,我用SqlDataSource(請參閱下面的代碼)填充數據庫值。asp.net dropdownlist - 在db值之前添加空白行

如何在值之前添加自己的文本或空白行?

<asp:DropDownList ID="drpClient" runat="server" Width="200px" 
    AutoPostBack="True" DataSourceID="dsClients" DataTextField="name" 
     DataValueField="client_id"> 
</asp:DropDownList> 
<asp:SqlDataSource ID="dsClients" runat="server" 
    ConnectionString="my_connection_string" 
    ProviderName="System.Data.SqlClient" 
    SelectCommand="SELECT [client_id], [name] FROM [clients]"> 
</asp:SqlDataSource> 

謝謝。

P.S.你推薦使用SqlDataSource還是以另一種方式填充?

+0

這涉及到:http://stackoverflow.com/questions/267064/asp-net-add-blank-item-at-top-of-dropdownlist – mcfea 2014-04-16 23:19:03

回答

50

您可以簡單地在DropDownList標記中添加ListItem。之後所有來自DataSource的值將被附加。

<asp:DropDownList ID="drpClient" runat="server" Width="200px" 
      AutoPostBack="True" DataSourceID="dsClients" DataTextField="name" 
      DataValueField="client_id" AppendDataBoundItems="true"> 
    <asp:ListItem>-- pick one --</asp:ListItem> 
</asp:DropDownList> 
+6

你必須告訴它'附加'而不是'替換' – 2009-06-11 21:22:20

+0

正如你所說,很容易錯過:-) – 2009-06-11 21:24:12

20
<asp:DropDownList ID="drpClient" runat="server" Width="200px" 
     AutoPostBack="True" DataSourceID="dsClients" DataTextField="name" 
     DataValueField="client_id" AppendDataBoundItems="True"> 

    <asp:ListItem Text="" Value="" /> 
</asp:DropDownList> 

這很容易錯過,所以不要忘記我添加的AppendDataBoundItems屬性。

6

我還沒有真正測試過這個,但我假設你可以在綁定下拉列表後添加一個項目。您可以將此事件添加到您希望將此空白框添加到的任何下拉列表中。

protected void DropDownList_DataBound(object sender, EventArgs e) 
    { 
     DropDownList ddl = (DropDownList)sender; 
     ListItem emptyItem = new ListItem("", ""); 
     ddl.Items.Insert(0, emptyItem); 
    } 
2

我解決改變選擇命令添加一個空的選項:

 <asp:SqlDataSource ID="dsClients" runat="server" 
      ConnectionString="my_connection_string" 
      ProviderName="System.Data.SqlClient" 
      SelectCommand="SELECT [client_id], [name] FROM [clients] union SELECT NULL, '--- pick one ----' "> 
     </asp:SqlDataSource> 

問候!

1

在剃刀式實現我它看起來像這樣:

@Html.EnumDropDownListFor(
    model => model.Privilege.Role, 
    "-- Select role --", 
    new 
    { 
     @style = "width: 216px !important", 
     @class = "form-control", 
     id = "role", 
     required = "required" 
    }) 

而在JavaScript中這是對負載執行我有這樣的:

function PutDefaultPrivilegePanelListHints() { 
    $('#role').val(''); 
    ... 
} 

還有通過不顯眼的更靈活的解決方案驗證(不依賴於HTML5):

$('.required').each(function() { $(this).rules('add', { required: true, messages: { required: '' } }) }); 

當然,有一個server-sid也檢查。 我不認爲應對課堂是個好主意。例如,我在頁面上顯示的所有內容都是一些類。這個類有幾個枚舉類型的屬性。複製所有這些屬性將是一場噩夢,但在某些額外的類中使它們爲空是有道理的,就像在這裏通過stackoverflow建議的那樣。

畢竟,爲什麼我應該爲了某些特定的標記而改變業務邏輯?相反,我通過javascript和一些模型檢查來處理所有事情。