asp.net 2个ListBox之间转移数据的实现

      2个ListBox之间转移数据,通常左侧的是从数据库动态读取出来的数据,然后右侧是用户从左侧选择数据项后添加的,这种情况在设置权限等场合经常用到,如下图:

asp.net 2个ListBox之间转移数据的实现_第1张图片


功能实现起来也很简单,实现方法如下:

   

    /// <summary>
    /// 选择
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnSave_Click(object sender, EventArgs e)
    {
        int count = listBox1.Items.Count;
        int index = 0;
        for (int i = 0; i < count; i++)
        {
            ListItem item = listBox1.Items[index];
            if (listBox1.Items[index].Selected == true)
            {
                listBox1.Items.Remove(item);
                listBox2.Items.Add(item);
                index--;
            }
            index++;
        }
    }



    /// <summary>
    /// 取消
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnCancel_Click(object sender, EventArgs e)
    {
        int count = listBox2.Items.Count;
        int index = 0;
        for (int i = 0; i < count; i++)
        {
            ListItem item = listBox2.Items[index];
            if (listBox2.Items[index].Selected == true)
            {
                listBox2.Items.Remove(item);
                listBox1.Items.Add(item);
                index--;
            }
            index++;
        }
    }





   /// <summary>
    /// 全部选择
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnSaveAll_Click(object sender, EventArgs e)
    {
        //定义中间动态存储    
        ArrayList arrRight = new ArrayList();
        //读取左边listbox的item的选中项    
        foreach (ListItem item in this.listBox1.Items)
        {
            arrRight.Add(item);
        }
        //执行右移操作    
        foreach (ListItem item in arrRight)
        {
            this.listBox2.Items.Add(item);
            this.listBox1.Items.Remove(item);
        }
    }



    /// <summary>
    /// 全部取消
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnCancelAll_Click(object sender, EventArgs e)
    {
        ArrayList arrLeft = new ArrayList();
        //读取右边listboxitem的选中项    
        foreach (ListItem item in this.listBox2.Items)
        {
            arrLeft.Add(item);
        }
        //执行左移操作    
        foreach (ListItem item in arrLeft)
        {
            this.listBox1.Items.Add(item);
            this.listBox2.Items.Remove(item);
        }
    }





你可能感兴趣的:(asp.net 2个ListBox之间转移数据的实现)