ListBox绑定数据库两种方法 dropdownlist


1. 绑定数据库的方法

 SqlConnection con=new SqlConnection("server=(local);database=department;uid=sa;pwd=");con.Open();
SqlCommand cm
=new SqlCommand("select empID,empName from emp",con);
SqlDataReader dr
=cm.ExecuteReader();//绑定
this.lbxEmp.DataSource=dr;        //lbxEmp为ListBox对象
this.lbxEmp.DataTextField="empName";
this.lbxEmp.DataValueField="empID";
this.lbxEmp.DataBind();
dr.Close();con.
Close();

2. 使用集合添加

SqlConnection con=new SqlConnection("server=(local);database=department;uid=sa;pwd=");
con.Open( );
SqlCommand cm
=new SqlCommand("select empID,empName from emp",con);
SqlDataReader dr
=cm.ExecuteReader( );
while(dr.Read( ))
{     
 
this.lbxEmp.Items.add(new listItem(dr.GetString(1),dr.GetInt32(0).ToString( )));
}

dr.Close( );
con.Close( );

3.  为DropDownList添加第一项

  this.DropDepartment.Items.Insert(0,new ListItem("请选择部门"));

posted on 2010-02-11 13:57  渔人码头  阅读(193)  评论(0编辑  收藏  举报

导航