ASP.NET ListBox内容复制和删除

前台代码,仅仅是很普通的一个页面。页面中存在2个Listbox和2个button按钮:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>




    


    



 

后天代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Bll;
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            //这里是我自己写的绑定数据源
            ListBox1.DataSource = BllEntity.GetAllCity();
            ListBox1.DataTextField = "CityName";
            ListBox1.DataValueField = "Id";
            ListBox1.Rows = BllEntity.GetAllCity().Count + 1;
            ListBox2.Rows = BllEntity.GetAllCity().Count + 1;
            ListBox1.DataBind();
        }
    }
    /// 
    /// 将左边的Listbox选中项 移动到右侧。允许选中多条
    /// 
    /// 
    /// 
    protected void Button1_Click(object sender, EventArgs e)
    {
        for (int i = 0; i < ListBox1.Items.Count - 1; i++)
        {
            if (ListBox1.Items[i].Selected)
            {

                for (int j = 0; j < ListBox2.Items.Count; j++)
                {
                    if (ListBox2.Items[j].Value == ListBox1.Items[i].Value)
                    {
                        ListBox2.Items.Remove(ListBox2.Items[j]);
                    }
                }
                ListBox2.Items.Add(ListBox1.Items[i]);
            }
        }
        ListBox2.ClearSelection();

    }
    /// 
    /// 将右侧的Listbox选中项从中删除掉
    /// 注意,此处用的是递减for循环。因为没删除一个子项,Listbox的Items都会减少1个
    /// 具体为什么这么写,大家自己考虑
    /// 
    /// 
    /// 
    protected void Button2_Click(object sender, EventArgs e)
    {
        ListItem[] lstItem = new ListItem[ListBox2.Items.Count];
        for (int i = ListBox2.Items.Count - 1; i >= 0; i--)
        {
            if (ListBox2.Items[i].Selected)
            {
                ListBox2.Items.Remove(ListBox2.Items[i]);
            }
        }
        ListBox2.ClearSelection();
    }
}


ListBox的 这个属性SelectionMode="Multiple"  是启用多选状态。

你可能感兴趣的:(c#开发技术)