您的位置:首页 > 其它

webform中listbox运用,2个相互传值练习1:

2015-10-12 16:53 375 查看


AppendDataBoundItems(将数据绑定项追加到静态声明列表项上)属性改为Ture;SelectionMode(列表的选择模式改为多项)属性改为Multiple

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{  if(!IsPostBack)
{
testDataContext _contect = new testDataContext();
ListBox1.DataSource=  _contect.Nation;
ListBox1.DataTextField = "Name";
ListBox1.DataValueField = "Code";
ListBox1.DataBind();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
int n = 0;
//用foreach去循环判断ListBox1.Items集合中每一项是否被选中
foreach(ListItem item in ListBox1.Items )
{
//首先判断是否有没有被选中,需要在外定义一个int n=0;变量,如果n大于零有被选中,就可以在另一个listbox中添加
if(item.Selected)
{
n++;

}
}
//判断n的值
if (n == 0)
{

}
else
{
foreach(ListItem item in ListBox1.Items)
{
//如果被选中添加
if (item.Selected)
{
//如果在listbox2中含有添加的,进行判断,如果重复不操作,没有的添加进去
if (ListBox2.Items.Contains(item))
{ }
else
{ ListBox2.Items.Add(item); }
}
}
}

}
protected void Button2_Click(object sender, EventArgs e)
{
//给ListBox2全部添加时先清空下
ListBox2.Items.Clear();//清空ListBox2数据
foreach (ListItem item in ListBox1.Items)
{
ListBox2.Items.Add(item);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: