两种方法:
采用//使用DataReader读取速度更快 :
private void Button1_Click(object sender, System.EventArgs e)
{
//取得Web.config里的数据库连接字串
string ConnString = ConfigurationSettings.AppSettings["ConnectionString"];
//创建一个SqlConnection
SqlConnection Conn = new SqlConnection( ConnString );
string SQL_Select = "select id, ItemName from DDLItem order by id desc";
//创建一个SqlCommand
SqlCommand myCommand = new SqlCommand( SQL_Select, Conn );
//读取数据记录并绑定
myCommand.Connection.Open();
//使用DataReader读取速度更快
SqlDataReader myReader = myCommand.ExecuteReader();
while ( myReader.Read() )
{
DropDownList1.Items.Add( new ListItem( myReader["ItemName"].ToString(),myReader["id"].ToString() ) );//增加Item
//或者这样也能绑定,
//DropDownList1.Items.Add( new ListItem( myReader[1].ToString(),myReader[0].ToString() ) );//增加Item
//都是要在知道Sql语句或者数据表结构的前提下才能这样绑定
}
myCommand.Connection.Close();
}
}
}
编译运行后,效果一样,但是更节省了系统的开销。而且我们也可以方面的添加特别的Item,比如这样:
采用Dataset:
private void Button1_Click(object sender, System.EventArgs e)
{
//取得Web.config里的数据库连接字串
string ConnString = ConfigurationSettings.AppSettings["ConnectionString"];
//创建一个SqlConnection
SqlConnection Conn = new SqlConnection( ConnString );
string SQL_Select = "select id, ItemName from DDLItem order by id desc";
//构造一个SqlDataAdapter
SqlDataAdapter myAdapter = new SqlDataAdapter( SQL_Select, Conn);
//开始读取数据
Conn.Open();
DataSet dataSet = new DataSet();
myAdapter.Fill( dataSet,"Table1" );
Conn.Close();
//开始绑定DropDownList
//指定DropDownList使用的数据源
DropDownList1.DataSource = dataSet.Tables["Table1"].DefaultView;
//指定DropDownList使用的表里的那些字段
DropDownList1.DataTextField = "ItemName"; //dropdownlist的Text的字段
DropDownList1.DataValueField = "id";//dropdownlist的Value的字段
DropDownList1.DataBind(); }}