说明:
选中做左边LisaBox中的信息,可以多选,点击“添加”按钮,可将其信息移到右边的ListBox中,同时左边被选中的信息消失,同理,点击”移除“按钮右边的信息就会还原到左边
代码:
前台:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="shangke.WebForm1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ListBox ID="ListBox1" runat="server" Height="266px" Width="157px"
SelectionMode="Multiple">
<asp:ListItem Value="0">张三</asp:ListItem>
<asp:ListItem Value="1">李四</asp:ListItem>
<asp:ListItem Value="2">王五</asp:ListItem>
<asp:ListItem Value="3">诸葛亮</asp:ListItem>
<asp:ListItem Value="4">刘备</asp:ListItem>
<asp:ListItem Value="5">张飞</asp:ListItem>
</asp:ListBox>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="添加" />
<asp:Button ID="Button2" runat="server" Text="移除" onclick="Button2_Click" />
<asp:ListBox ID="ListBox2" runat="server" Height="265px" Width="185px"
SelectionMode="Multiple">
</asp:ListBox>
</div>
</form>
</body>
</html>
后台:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
namespace shangke
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
#region MyRegion
List<ListItem> list = new List<ListItem>();
for (int i = ListBox1.Items.Count - 1; i >= 0; i--)
{
if (ListBox1.Items[i].Selected == true)
{
list.Add(ListBox1.Items[i]);
ListBox1.Items.Remove(ListBox1.Items[i]);
}
}
for (int i = list.Count - 1; i >= 0; i--)
{
ListBox2.Items.Add(list[i]);
}
#endregion
#region MyRegion
//foreach (ListItem li in ListBox1.Items)
//{
// if (li.Selected)
// {
// ListBox2.Items.Add(li);
// }
//}
//for (int i = this.ListBox1.Items.Count - 1; i >= 0; i--)
//{
// if (this.ListBox1.Items[i].Selected)
// {
// this.ListBox1.Items.RemoveAt(this.ListBox1.Items.IndexOf(this.ListBox1.Items[i]));
// }
//}
#endregion
}
protected void Button2_Click(object sender, EventArgs e)
{
foreach (ListItem li in ListBox2.Items)
{
if (li.Selected)
{
ListBox1.Items.Add(li);
}
}
for (int i = this.ListBox2.Items.Count - 1; i >= 0; i--)
{
if (this.ListBox2.Items[i].Selected)
{
this.ListBox2.Items.RemoveAt(this.ListBox2.Items.IndexOf(this.ListBox2.Items[i]));
}
}
}
}
}