DropdownList 绑定hashTable,dictionary

在DropDownList中有值域和文本域,在程序开发中经常要确切的绑定两个域。在好多情况下,我们页面显示的是文本,而在数据库存储的是这种文本标 识的整数,如此可以利用Dictionary建立对象,将数据库存储的值与页面显示的值联系起来,进行简单的转换,并且这样还可以实现值或者文本的检索功 能。灵活,很适合进行程序开发。
关键代码:
1         DropDownList1.DataTextField  =  " value " ;
2         DropDownList1.DataValueField  =  " key " ;
3         DropDownList1.DataSource  =  getTypeList();
4         DropDownList1.DataBind();

实例代码:

 1    protected void Button1_Click(object sender, EventArgs e)
 2    {
 3        DropDownList1.DataTextField = "value";
 4        DropDownList1.DataValueField = "key";
 5        DropDownList1.DataSource = getTypeList();
 6        DropDownList1.DataBind();
 7    }

 8    public Dictionary<intstring> getTypeList()
 9    {
10        Dictionary<intstring> list = new Dictionary<intstring>();
11        list.Add(1"L1用户");
12        list.Add(2"L2用户");
13        list.Add(3"赢富用户");
14        list.Add(4"股指期货用户");
15        return list;         
16    }

17    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
18    {
19        Response.Write(DropDownList1.SelectedValue.ToString());
20    }
要为dropdownlist绑定数据库中的数据,可以按照以下步骤操作: 1. 在页面中添加一个dropdownlist控件。 2. 在页面的代码-behind中编写代码来连接数据库并查询需要绑定的数据。比如使用ADO.NET中的SqlConnection和SqlCommand类来连接数据库并执行查询操作。 3. 将查询结果绑定dropdownlist控件上。可以使用dropdownlist控件的DataSource属性来指定数据源,使用DataTextField和DataValueField属性来指定要显示的文本和值的字段名,最后调用DataBind方法来完成绑定。 以下是一个简单的示例代码: ```c# protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { string connectionString = "Data Source=your_server;Initial Catalog=your_database;User ID=your_username;Password=your_password"; string query = "SELECT id, name FROM your_table"; SqlConnection connection = new SqlConnection(connectionString); SqlCommand command = new SqlCommand(query, connection); SqlDataAdapter adapter = new SqlDataAdapter(command); DataSet dataSet = new DataSet(); adapter.Fill(dataSet, "your_table"); dropdownlist.DataSource = dataSet.Tables["your_table"]; dropdownlist.DataTextField = "name"; dropdownlist.DataValueField = "id"; dropdownlist.DataBind(); } } ``` 在这个示例中,我们从名为your_table的表中查询了id和name两个字段的数据,并将其绑定到了名为dropdownlistdropdownlist控件上。其中,数据库连接字符串、查询语句、数据源字段名和值字段名需要根据实际情况进行修改。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值