http://s3/middle/4fcce4b0gbbe40d759ba2&690
VS2008下,设计页面上拖放四个ListBox,ID默认。
法一:静态添加法。
对ListBox1的列表采用,将<asp:ListItem>元素作为列表控件的子级输入
<asp:ListBox ID="ListBox1"
runat="server">
<asp:ListItem Text="one"
Value="1"></asp:ListItem>
<asp:ListItem Text="Two"
Value="2"></asp:ListItem>
<asp:ListItem Text="Three"
Value="3"></asp:ListItem>
</asp:ListBox>
也可用再添加Selected属性,设置选中。
法二:Items.Add函数添加。对ListBox2的列表采用,定义如下函数:
private void
ListBoxBindAdd()
{
this.ListBox2.Items.Clear();
this.ListBox2.Items.Add(new ListItem("one", "1"));
this.ListBox2.Items.Add(new ListItem("two", "2"));
this.ListBox2.Items.Add(new ListItem("three", "3"));
}
法三:AddRange函数。对ListBox3的列表采用,定义如下函数:
private void ListBoxBindAddRange()//
{
this.ListBox3.Items.Clear();
ListItem[] myArr=new ListItem[3];
for(int i=0;i<myArr.Length;i++)
myArr[i]=new ListItem();
myArr[0].Text="One";
myArr[0].Value="1";
myArr[1].Text="Two";
myArr[1].Value="2";
myArr[2].Text="Three";
myArr[2].Value="3";
this.ListBox3.Items.AddRange(myArr);
}
说明:myArr定义的是对象数组,所以对于其中的每一个分量,都要用for循环实例化对象元素,否则提示出错。
AddRange方法用于将ListItem对象数组的项添加到集合。
法四:纯一维数组的方式,使其成为数据源,调用DataBind()函数绑定。对ListBox4的列表采用,定义如下函数:
private void ListBoxDataBind()
{
this.ListBox4.Items.Clear();
string[] myArr = new string[3];
myArr[0] = "oneAR";
myArr[1] = "twoAR";
myArr[2] = "threeAR";
this.ListBox4.DataSource = myArr;
this.ListBox4.DataBind();
}
以上三个函数通过如下方式被调用:
protected void Page_Load(object sender, EventArgs e)
{
if (!this.Page.IsPostBack)
{
ListBoxBindAdd();
ListBoxBindAddRange();
ListBoxDataBind();
}
}
加载中,请稍候......