[英]asp.net dropdown list default value that does not exist in sql table
嗨,这是我在这个网站上的第一个问题
我有一个带有下拉列表的Web表单,该表单是从我的数据库sql-server 2012中填充的。
我的表具有诸如genderID和genderName之类的值,并且它填充了下拉列表,但是当页面加载事件触发“选择性别”时,我还想显示默认值。
我可以将此值添加到要在下拉列表中显示的数据库中,但这不是完美的解决方案,因为这意味着我已经在sql server中输入了无效数据。 我如何在下拉列表中显示此默认值,而该默认值在sql server表中实际上并不存在。
我的代码后面:
using(SqlConnection con = new SqlConnection(cs))
{
using(SqlCommand cmd = new SqlCommand("select * from dbo.Gender", con))
{
con.Open();
DropDownList1.DataSource = cmd.ExecuteReader();
DropDownList1.DataTextField = "GenderName";
DropDownList1.DataValueField = "ID";
DropDownList1.DataBind();
}
}
页面加载后,它应在下拉列表中显示“选择性别”。
您无需在数据库中添加条目即可在下拉列表中显示该默认值。 您可以简单地初始化一个ListItem对象,并将其插入到索引为0的下拉列表中。
请记住,您的下拉列表是ListItem对象的集合,因此请初始化ListItem类型的对象并将其添加到下拉列表中。
就像是 ......
using(SqlConnection con = new SqlConnection(cs))
{
using(SqlCommand cmd = new SqlCommand("SELECT * FROM dbo.Gender", con))
{
con.Open();
DropDownList1.DataSource = cmd.ExecuteReader();
DropDownList1.DataTextField = "GenderName";
DropDownList1.DataValueField = "ID";
DropDownList1.DataBind();
ListItem li = new ListItem("Select Gender", "-1");
DropDownList1.Items.Insert(0, li);
}
}
在将数据绑定到下拉列表之后,请执行以下操作:
DropDownList1.Items.Insert(0, new ListItem("Select gender","")
绑定后,类似的东西会起作用:
DropDownList1.Items.Insert(0, new ListItem("Select Gender","-1")
另一种选择是在选择语句中使用UNION ALL添加项目。
这是示例:
using(SqlConnection con = new SqlConnection(cs))
{
using(SqlCommand cmd = new SqlCommand("select 'Select Gender' genderName, 0 genderID UNION ALL select genderName, genderId from Gender", con))
{
con.Open();
DropDownList1.DataSource = cmd.ExecuteReader();
DropDownList1.DataTextField = "genderName";
DropDownList1.DataValueField = "genderID";
DropDownList1.DataBind();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.