【问题标题】:How to add a Default text on Drop Down List?如何在下拉列表中添加默认文本?
【发布时间】:2015-07-08 22:41:13
【问题描述】:

我很难将默认文本添加到下拉列表中。 我想在我的下拉列表中添加一个默认的“选择部门...”文本。文本根本没有任何价值,并且在选择时永远不会添加到数据库中。它只是一个显示,就像给用户的指令。


void GetUserTypes()
{
    con.Open();
    SqlCommand cmd = new SqlCommand();
    cmd.Connection = con;
    cmd.CommandText = "SELECT TypeID, TypeName FROM Types";
    SqlDataReader dr = cmd.ExecuteReader();
    ddlTypes.DataSource = dr;
    ddlTypes.DataTextField = "TypeName";
    ddlTypes.DataValueField = "TypeID";
    ddlTypes.DataBind();
    con.Close();
}

    <!--Department-->
    <div class="form-group">
        <label class="control-label col-lg-4">
            Department</label>
        <div class="col-lg-8">
            <asp:DropDownList ID="ddlTypes" runat="server" class="form-control" />
        </div>
    </div>

我已尝试添加 AppendDataBoundItems,但问题是当我提交表单时,下拉列表中的选定项目为“选择部门...”时会出错。

【问题讨论】:

  • Carlitrosss 的回答应该可以满足您的需求。应该注意的是,设置 `AppendDataBoundItems=True' 确保您的数据源项将被附加,而不会删除标记中添加的初始项。

标签: c# asp.net


【解决方案1】:

在标记中直接添加一个ListItem怎么样,比如:

<asp:DropDownList runat="server" ID="ddlTypes" AppendDataBoundItems="true">
    <asp:ListItem Text="Select value..." Value="0" Selected="True"></asp:ListItem>
</asp:DropDownList>

确保 AppendDataBoundItems="true" 存在。 在您的事件侦听器或验证中,检查 dllTypes.SelectedValue != 0。

【讨论】:

    【解决方案2】:
    ddlTypes.DataBind();
    ddlType.Insert(0,new ListItem("","Select a department..."))
    

    提交的时候需要检查ddlType的值,就像

    if(ddlType.SelectedIndex>0)
    {
        //your code
    }
    

    【讨论】:

      猜你喜欢
      • 2016-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多