2.代脊迹码循环添加
for(int i=0i<100i++)
{
ListItem item=new ListItem(i.ToString(),"手动添加"+i.ToString())
dropdownList.Items.Add(item)
}
3.还可以手动添加
第一伍逗液步:连接数据库第二步:取得数据/
第三步:为指蚂其指定数据源
第四步:指定其text和value值。
第五步腔物:绑定
参考代码:
SqlConnection con3=new SqlConnection("Server=.user id=sapassword=123456Database=FABS")
con3.Open()
SqlCommand cmd3=new SqlCommand()
cmd3.CommandText="select * from sheng"
cmd3.CommandType=CommandType.Text
cmd3.Connection=con3
SqlDataReader sdr3=cmd3.ExecuteReader()
DropDownList1.DataSource =sdr3
DropDownList1.DataTextField = "shengming"
DropDownList1.DataBind()
con3.Close()
//比如我写一个类,类里有一个数据绑定的方法。示例代码如下class datasouce
{
//数据绑定的方法
public void getAll()
{
//代码略
}
}
//然后我到页面中去调用,比如我有一个dispaly页面,那肯定就会有一个display类
class diplay
{
//实例化数据绑定的类:datasouce
datasouce da = new datasouce()
//绑定getAll()数据衫兆丛查询的方法
this.DropDownList1.DataSource = da.getAll()
this.DropDownList1.DataTextField = "字段(比如用户名字段猜老啊,反正是你数据表里有的字段)"
this.DropDownList1.DataValueField = "ID字段(就是你该表的ID字段)"
this.DropDownList1.DataBind()
}
题外话
另外,无论你查询方法是用的dataset还是泛型,都可以这样写。DropDownList1绑定数据的那段或樱代码不会有任何变动。。
所以我强烈介意用泛型去实现,因为用泛型避免了装箱和拆箱,速度快,而且你还可以通过获取到的值在返回查询,方便其扩展
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)