填充下拉列表控件以及“请选择一个值”选项
我正在从数据库填充下拉列表控件。然而,当我在运行时显示下拉菜单时,我希望第一个可见选项是“请选择一名教职人员”(这将是选项值 0)。 我怎样才能做到这一点?
SqlConnection con = new SqlConnection(strConn);
string sqlFacultyMember = "usp_GetFacultyMember";
SqlCommand cmdFacultyMember = new SqlCommand(sqlFacultyMember, con);
cmdFacultyMember.CommandType = CommandType.StoredProcedure;
con.Open();
SqlDataAdapter ada = new SqlDataAdapter(cmdFacultyMember);
DataSet ds = new DataSet();
ada.Fill(ds);
ddlFacultyMember.DataSource = ds;
ddlFacultyMember.DataValueField = "UserID";
ddlFacultyMember.DataTextField = "FullName";
ddlFacultyMember.DataBind();
I am populating a dropdownlist control from a database. That happes fine, however, when I display the dropdown at runtime, I want the first visible option to be "Please select a faculty member" (which would be option value 0).
How can I accomplish that?
SqlConnection con = new SqlConnection(strConn);
string sqlFacultyMember = "usp_GetFacultyMember";
SqlCommand cmdFacultyMember = new SqlCommand(sqlFacultyMember, con);
cmdFacultyMember.CommandType = CommandType.StoredProcedure;
con.Open();
SqlDataAdapter ada = new SqlDataAdapter(cmdFacultyMember);
DataSet ds = new DataSet();
ada.Fill(ds);
ddlFacultyMember.DataSource = ds;
ddlFacultyMember.DataValueField = "UserID";
ddlFacultyMember.DataTextField = "FullName";
ddlFacultyMember.DataBind();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您还可以在绑定后将项目添加到 DropDownList,如下所示:
我喜欢这种方法的一点是,它将添加到 UI 中,我认为它属于 UI,因为这对用户来说是一种方便,而不是您真正想要对其采取行动的数据。
You can also add the item to the DropDownList after you bind it like so:
What I like about this approach is it leaves the adding of this to the UI, where I think it belongs, since this is a convenience for the user, not a piece of data you actually want to action on.
您需要在
DataSet
中的位置 0 处插入一条记录,其中Value = "0"
和Text = "Please Select a Value"
。You need to insert a record at position 0 in the
DataSet
withValue = "0"
andText = "Please Select a Value"
.您需要设置 AppendDataBoundItems 设置为 true。另外,在您的 SelectionIndexChanged 事件中检查所选索引是否不为零。
You need to set the AppendDataBoundItems to true for your DropDownList. Also in your selectionindexchanged event check if the selected index is not zero.