arraylist 怎么绑定到dropdownlist

2024-12-05 04:33:20
推荐回答(3个)
回答1:

我已经测试过了 没问题。
ArrayList arr = new ArrayList();
Class1 c1 = new Class1 ();
c1.a = 11;
c1.b = 12;
arr.Add(c1.a);
arr.Add(c1.b);
Class1 c2 = new Class1 ();
c2.a = 21;
c2.b = 22;
arr.Add(c2.a);
arr.Add(c2.b);
ListItemCollection listBoxData = new ListItemCollection();
for (int i = 0; i < arr.Count;i++ )
{
listBoxData.Add(new ListItem(arr[i].ToString(), arr[i].ToString()));

}
DropDownList1.DataSource = listBoxData;
DropDownList1.DataBind();

回答2:

DropDownList2必须设置DataValueField和DataTextField属性,来指明DropDownList要显示的Value和Text,这要看你的Class1怎么定义的了

假设
public class Class1
{
public int Id { get; set; }
public string Text { get; set; }
}
那么可以
this.DropDownList2.DataSource = arr;
this.DropDownList2.DataTextField = "Text";
this.DropDownList2.DataValueField = "Id";
this.DropDownList2.DataBind();

回答3:

在Class1中将a和b封装成字段
class Class1
{
int a;

public int A
{
get { return a; }
set { a = value; }
}
int b;

public int B
{
get { return b; }
set { b = value; }
}
}

数据绑定代码如下
DropDownList1.DataTextField = "A";
DropDownList1.DataValueField = "B";
DropDownList1.DataSource = arr;
DropDownList1.DataBind();