15.12.14listbox列表框

ListBox 列表框

autopostback:true:

if(!ispostback)
{
}

1:绑定数据:
if(!IsPostBack)
{
NationDataContext context = new NationDataContext();
ListBox1.DataSource = context.Nation;
ListBox1.DataTextField = "Name";
ListBox1.DataValueField = "Code";
ListBox1.DataBind();
}}


2:获取选中项的值
单选:Label1.Text= ListBox1.SelectedValue.ToString();
多选:属性>selectionmode>mutiple可单选

protected void Button1_Click(object sender, EventArgs e)
{

foreach (ListItem item in ListBox1.Items)
{
if (item.Selected)
{
Label1.Text +=item.Value;
}

}
3:设置选中项

protected void Button2_Click(object sender, EventArgs e)
{

foreach (ListItem item in ListBox1.Items)
{
if (item.Text == "汉族" || item.Text == "满族")
{
item.Selected = true;

}

}

}

4:练习:

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

public partial class lizi : System.Web.UI.Page
{

//加载绑定数据
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
NationDataContext context = new NationDataContext();
ListBox1.DataSource = context.Nation;
ListBox1.DataTextField = "Name";
ListBox1.DataValueField = "Code";
ListBox1.DataBind();


}
}
//单选。多选
protected void Button1_Click(object sender, EventArgs e)
{


foreach (ListItem item in ListBox1.Items)
{
if (item.Selected)
{
if(! ListBox2.Items.Contains(item))//如果列表框2中不包含此数据则添加否则不添加,防止重复添加
{
ListBox2.Items.Add(item);
}}

 

}
}

//全选
protected void Button2_Click(object sender, EventArgs e)
{
foreach (ListItem item in ListBox1.Items)
{

if (!ListBox2.Items.Contains(item))//如果列表框2中不包含此数据则添加否则不添加,防止重复添加
{
ListBox2.Items.Add(item);

}

 

}
}
}

 

posted @ 2015-12-15 15:13  小热包1  阅读(115)  评论(0编辑  收藏  举报