选择另一个时取消选择列表框

时间:2018-07-18 18:11:10

标签: c# winforms listbox

我有两个类似此照片的列表框:

enter image description here

如您所见,选择了两侧。我想知道当单击另一个列表时如何取消选择一个列表。有可能吗?

2 个答案:

答案 0 :(得分:1)

以下代码可能会帮助您解决问题,但是您也可以在函数的selectedIndexChanged事件上添加clearSelected函数。

    namespace StackoverFlow4
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            button1.Text = "UnSelected";
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            button1.Text = "Selected";
            pictureBox1.BackgroundImage = StackoverFlow4.Properties.Resources.tick;
            button1.Text = "Clear Selected";
        }

        private void button1_Click(object sender, EventArgs e)
        {
            listBox1.ClearSelected();
            listBox2.ClearSelected();
            button1.Text = "UnSelected";
            pictureBox1.BackgroundImage = StackoverFlow4.Properties.Resources.cross;
            pictureBox2.BackgroundImage = StackoverFlow4.Properties.Resources.cross;
        }

        private void listBox2_SelectedValueChanged(object sender, EventArgs e)
        {
            pictureBox2.BackgroundImage = StackoverFlow4.Properties.Resources.tick;
            button1.Text = "Clear Selected";
        }
    }
}

首先两个都未被选中 enter image description here 清除列表(如果要选择) enter image description here 如果两者都选中,则清除两者 enter image description here

我在这里太新了,对不起 保持祝福

答案 1 :(得分:0)

您只需要在相应的列表框中为SelectedIndexChange添加一个事件侦听器,如下所示:

    // Have Box1 deselect any Box2 inputs on index change.
    private void listBox1_SelectedIndexChanged(object sender, EventArgs e) {
        listBox2.ClearSelected();
    }

    // Have Box2 deselect any Box1 inputs on index change.
    private void listBox2_SelectedIndexChanged(object sender, EventArgs e) {
        listBox1.ClearSelected();
    }

要检出的其他资源:Unselect All Items in a Listbox