asp教程.net dropdownlist动态绑定的两种方法
动态绑定方法一:动态绑定数据库教程中的字段。
sqlconnection conn = utilitysqlclass.operatedatabase.returnconn();
string strsql = "select * from companytype";
sqldataadapter ada = new sqldataadapter(strsql, conn);
dataset ds = new dataset();
ada.fill(ds, "companytype");
dropdownlist1.datasource = ds.tables["companytype"].defaultview;
dropdownlist1.datavaluefield = ds.tables["companytype"].columns[1].columnname;
dropdownlist1.datatextfield = ds.tables["companytype"].columns[1].columnname;
dropdownlist1.databind();
ds.dispose();
动态绑定方法二:利用dropdownlist.items.add方法。
protected void page_load(object sender, eventargs e)
{
if (!ispostback)
{
sqlconnection conn = utilitysqlclass.operatedatabase.returnconn();
try
{
conn.open();
this.dropdownlist1.items.add("");
string strsql = "select companytype from companytype";
sqlcommand com = new sqlcommand(strsql, conn);
sqldatareader dr = com.executereader();
while (dr.read())
{
this.dropdownlist1.items.add(dr["companytype"].tostring());
}
}
catch (exception ex)
{
response.write("alert('" + ex.message.tostring() + "')");
}
finally
{
conn.close();
}
}
}
第一种方法:
string connstring = configurationsettings.apps教程ettings["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();
第二种方法:
con.open();
sqlcommand cmd = new sqlcommand(strsql,con);
sqldatareader dr = cmd.executereader();
while (dr.read())
{
dropdownlist1.items.add(new listitem(dr["status"].tostring(), dr["status_id"].tostring()));
}