您的位置:首页 > 运维架构

DropdownList下拉列表控件的使用

2010-04-20 20:25 357 查看
DropdownList下拉列表控件的使用

一,绑定数据
1.用代码的方式添加列表项(.cs)
this.DropDownList1.Items.Add(new ListItem("aaa"));
this.DropDownList1.Items.Add(new ListItem("bbb"));
this.DropDownList1.Items.Add(new ListItem("ccc"));
2.在html中 如何在下拉列表中添加项(.aspx)
<asp:DropDownList ID="DropDownList1" runat="server" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
<asp:ListItem Text ="111" Value="111"></asp:ListItem>
<asp:ListItem Text ="222" Value="222"></asp:ListItem>
<asp:ListItem Text ="333" Value="333"></asp:ListItem>
</asp:DropDownList>

3.在下拉列表中调用数组(.cs)
using System.Collections;引用命名空间(数组ArrayList)
ArrayList ar = new ArrayList();
ar.Add("qqq");
ar.Add("www");
ar.Add("eee");
this.DropDownList1.DataSource=ar;
this.DropDownList1.DataBind(); 绑定数据方法

4.使用创建DataTable动态绑定

DataTable dt = new DataTable();
dt.Columns.Add("id", typeof(String));
dt.Columns.Add("name", typeof(String));

DataRow dr = dt.NewRow();
dr["id"] = "0";
dr["name"] = "是";
dt.Rows.Add(dr);

dr = dt.NewRow();
dr["id"] = "1";
dr["name"] = "否";
dt.Rows.Add(dr);

this.DropDownList1.DataSource = dt;
this.DropDownList1.DataTextField = "name";// 设置相当于2 中的Text 在列表中显示出来的部分
this.DropDownList1.DataValueField = "id";//相当Value值
this.DropDownList1.DataBind();
this.DropDownList1.SelectedIndex = 1;//设置默认值

5.从数据库绑定数据

string str = "Data Source=.;Initial Catalog=ddl;User ID=sa;Password=111111";
string sql = "select * from UserName";
SqlConnection conn = new SqlConnection(str);
SqlDataAdapter dr = new SqlDataAdapter(sql,conn);

DataSet ds = new DataSet();//创建数据集;

this.DropDownList1.DataSource = ds.Tables[0];//也可以使用 ds.Tables[0].DefaultView 操作更多;
this.DropDownList1.DataTextField = "PrividerName";
this.DropDownList1.DataValueField = "UniqueID";
this.DropDownList1.DataBind();
ListItem item = new ListItem("不限", "0");//自定义添加一个
this.DropDownList1.Items.Insert(0, item);
this.DropDownList1.SelectedIndex = 0;//设置默认显示;

二,选中列表的数据传递给文本框 (注意:属性AutoPostback 设为true)
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
this.TextBox1.Text = this.DropDownList1.SelectedValue;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: