【发布时间】: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' 确保您的数据源项将被附加,而不会删除标记中添加的初始项。