如何在下拉列表中添加默认文本

本文关键字:添加 默认 文本 下拉列表 | 更新日期: 2023-09-27 18:01:37

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


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,但问题是,当我提交下拉列表中所选项目为"选择部门…"的表单时,会出现错误。

如何在下拉列表中添加默认文本

如何直接在标记中添加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.

ddlTypes.DataBind();
ddlType.Insert(0,new ListItem("","Select a department..."))

提交时,您需要检查ddlType的值,就像一样

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