DropDownList ListBox1 CheckBoxList1 RadioButtonList1 BulletedList1 绑定数据源方法(方法都一样) ListItem表示其中一项的实例 AppendDataBoundItems 如果不想在绑定后,复盖以前的项,就要开启该项
第一种: 数据源是数组或字符串
ListItem[] d1 = new ListItem[] { new ListItem("项目1", "1"), new ListItem("项目2", "2"), new ListItem("项目3", "3") };
DropDownList1.Items.Clear();
DropDownList1.Items.AddRange(d1);
DropDownList1.Items.Insert(0, new ListItem("请选择","0"));
说明:用以上方法进行绑定,如果指定数据源进行绑定(DropDownList1.DataSource = d1;DropDownList1.DataBind();),就会出现
DropDownList1.SelectedItem.Value=DropDownList1.SelectedItem.Text(只能得到text值,而得不到value)
第二种 : 数据源是数据库表
DataSet d3=new DataSet ();
using(SqlConnection conn=new SqlConnection (cn))
{
SqlDataAdapter dr=new SqlDataAdapter ("select * from admin",conn);
dr.Fill(d3);
}
DropDownList1.DataSource = d3.Tables[0];
DropDownList1.DataTextField = "username";
DropDownList1.DataValueField = "id";
DropDownList1.DataBind();
这时就可以得到DropDownList1 的text 或 value
第三种: 希哈值
Hashtable d2=new Hashtable (3);
d2.Add("项目1",1);
d2.Add("项目2",2);
d2.Add("项目3",3);
ListBox1.Items.Clear();
ListBox1.DataSource = d1;
ListBox1.DataTextField = "key";
ListBox1.DataValueField = "value";
ListBox1.DataBind();
第四种方法 文件系统
DirectoryInfo di = new DirectoryInfo(@"F:\");
DirectoryInfo[] d4 = di.GetDirectories();
RadioButtonList1.DataSource = d4;
RadioButtonList1.DataTextField = "name";
RadioButtonList1.DataValueField = "fullname";
RadioButtonList1.DataBind();
第五种方法 获取/设置类的值
public class link
{
private string _name;
private string _url;
public string name
{
get { return _name; }
set { _name = value; }
}
public string url
{
get { return _url; }
set { _url = value; }
}
public link(string x, string y)
{
name = x;
url = y;
}
}
ArrayList d5 = new ArrayList();
d5.Add(new link("新浪", "http://www.sina.com.cn/"));
d5.Add(new link("网易", "http://www.163.com/"));
BulletedList1.DataSource = d5;
BulletedList1.DataTextField = "name";
BulletedList1.DataValueField = "url";
BulletedList1.DataBind();
浙公网安备 33010602011771号