用ASP.NET怎样动态给dropdownlist控件赋值

用ASP.NET怎样动态给dropdownlist控件赋值,第1张

1.绑定核野饥改返数据

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绑定数据的那段或樱代码不会有任何变动。。

所以我强烈介意用泛型去实现,因为用泛型避免了装箱和拆箱,速度快,而且你还可以通过获取到的值在返回查询,方便其扩展


欢迎分享,转载请注明来源:内存溢出

原文地址: http://www.outofmemory.cn/bake/11971634.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-20
下一篇 2023-05-20

发表评论

登录后才能评论

评论列表(0条)

保存