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("请选择部门"));
本文介绍了如何将ListBox控件绑定到数据库以及如何通过集合添加数据,还详细讲解了如何为DropDownList添加首项,提供了两种不同的实现方式。

2075

被折叠的 条评论
为什么被折叠?



