asp.net下拉列表 - 在db值之前添加空行

时间:2009-06-11 21:12:12

标签: asp.net drop-down-menu sqldatasource dropdownbox

在我的网页上,我有DropDownList,其中填充了SqlDataSource的数据库值(请参阅下面的代码)。

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

<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或以其他方式填充?

5 个答案:

答案 0 :(得分:52)

您只需在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>

答案 1 :(得分:21)

<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属性。

答案 2 :(得分:6)

我还没有真正测试过这个,但我假设你可以在绑定下拉列表后添加一个项目。您可以将此事件添加到您要将此空框添加到的任何下拉列表中。

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

答案 3 :(得分:2)

我解决了更改select命令添加空选项的问题:

        <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>

问候!!!

答案 4 :(得分: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: '' } }) });

当然,也有服务器端检查。 我不认为应对课程是个好主意。 例如,我在页面中显示的所有内容都是一些类。该类有几个可枚举的类型属性。复制所有这些属性将是一场噩梦,但是在一些额外的类中使它们可以为空,就像在stackoverflow上建议的一样。

毕竟,为什么我会为了某些特定的标记而改变我的业务逻辑?相反,我通过javascript和一些模型检查来处理所有事情。