首页 > 代码库 > 操作可选列表框控件 CheckedListBox

操作可选列表框控件 CheckedListBox

下面演示如何利用 CheckedListBox 实现多选与移动选项:

注:1. 修改 CheckOnClick 属性为 True,可实现单击鼠标时就选中 Checkbox

      2. checkedListBox1.SelectedItems 只能获取高亮显示的那个选项,而且始终只返回一个选项

using System;
using System.Windows.Forms;

namespace WindowsFormsApp
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        //全部移动:左->右
        private void button1_Click(object sender, EventArgs e)
        {
            foreach (object o in checkedListBox1.Items)
            {
                checkedListBox2.Items.Add(o);
            }
            checkedListBox1.Items.Clear();
        }

        //只移动选中项:左->右
        private void button2_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < checkedListBox1.Items.Count; i++)
            {
                if (checkedListBox1.GetItemChecked(i))
                {
                    checkedListBox2.Items.Add(checkedListBox1.Items[i]);
                }
            }

            //清理左侧checkedListBox中已选中的项
            for (int j = 0; j < checkedListBox1.Items.Count; j++)
            {
//要判断Checkbox是否被选中,不能用checkedListBox1.SelectedItems
if (checkedListBox1.GetItemChecked(j)) { checkedListBox1.Items.Remove(checkedListBox1.Items[j]); //列表中移除一个元素后,需要重新循环查找 j = -1; } } } //只移动选中项:右->左 private void button3_Click(object sender, EventArgs e) { for (int i = 0; i < checkedListBox2.Items.Count; i++) { if (checkedListBox2.GetItemChecked(i)) { checkedListBox1.Items.Add(checkedListBox2.Items[i]); } } //清理左侧checkedListBox中已选中的项 for (int j = 0; j < checkedListBox2.Items.Count; j++) { if (checkedListBox2.GetItemChecked(j)) { checkedListBox2.Items.Remove(checkedListBox2.Items[j]); //列表中移除一个元素后,需要重新循环查找 j = -1; } } } //全部移动:右->左 private void button4_Click(object sender, EventArgs e) { foreach (object o in checkedListBox2.Items) { checkedListBox1.Items.Add(o); } checkedListBox2.Items.Clear(); } } }

运行结果:

技术分享 

操作可选列表框控件 CheckedListBox