asp.net 2個ListBox之間轉移資料的實現

暖楓無敵發表於2015-01-10

      2個ListBox之間轉移資料,通常左側的是從資料庫動態讀取出來的資料,然後右側是使用者從左側選擇資料項後新增的,這種情況在設定許可權等場合經常用到,如下圖:


功能實現起來也很簡單,實現方法如下:

   

    /// <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);
        }
    }





相關文章