给DropDownList 控件加上"==请选择=="选项

来源:互联网 发布:linux nat 端口转发 编辑:程序博客网 时间:2024/05/16 11:03

1.给VS2003下的DropDownList添加"==请选择=="选项的方法

private void Page_Load(object sender, System.EventArgs e)
{
 if(!IsPostBack)
 {
  String sql="select * from ClassInfo";
  SqlConnection con=new SqlConnection("server=.;uid=sa;pwd=sa;database=ManualAssign");
  SqlDataAdapter sda = new SqlDataAdapter(sql,con);
  DataSet ds =new DataSet();
  sda.Fill(ds, "ClassInfo");
  this.DropDownList1.DataSource = ds.Tables["ClassInfo"].DefaultView;
  this.DropDownList1.DataTextField = "ClassName";
  this.DropDownList1.DataValueField = "ClassId";
  this.DropDownList1.DataBind();
  this.DropDownList1.Items.Insert(0,new ListItem("==请选择==","-1"));//在Item中添加在第0项,该Item的text值为==请选择==,实际的value是-1,注意这句一定要写在this.DropDownList1.DataBind();绑定语句后,写在前面无效
  this.DropDownList1.Items.FindByValue("-1").Selected=true;
  this.DataGrid1.Visible=false;
 }
}
不加上If条件的话,无法选择下拉列表框的值,即使选中了也无法执行,因为当点击按钮时页面重新加载Load方法,默认还是选中“==请选择==”这个选项!

1.给VS2005下的DropDownList添加"==请选择=="选项的方法

请添加一个DropDownList 控件,后台写绑定语句,然后在其Items 中添加一个“==请选择==”项目。

最后一个关键点在于AppendDataBoundItems 属性,请将该属性设置为true,这样便能轻松完成功能的构建。

原创粉丝点击