0
votes

I jumped on a problem regarding listbox "selection" I already searched some around this topic but i didn't find the answers i am looking for. I'm OO programming and i want to use as less code as possible so it gotta be a "not to big" code.

I have 2 listboxes, when i selected an item in any listbox, the previously selected item gotta be unselected.. so i can only have 1 selection, when i select someting in listbox 1, and after that someting in listbox 2, it gotta "deselect" listbox1, so i want the selection "synced" with each other.

I hope i'm clear, ask me if you need some more information :)

thanks by forehand Ricje20

--EDIT--

I'm not done yet xD can i make it so that i can say in (for example) the following code selectedListbox.SelectedIndex or someting like that? i need to replace the listBox1, to "the selected listbox" by "the selected listbox" i mean the listbox where an item is selected

string file2 = files2[listBox1.SelectedIndex];

2

2 Answers

2
votes

I would implement the event of "SelectedItem_Changed" for both the Listbox. Then using a global bool variable for discriminating if an item of one listbox has been already selected. If an item of listbox1 is already selected, I would clear the selection from listBox1 and then select the item from listBox2.

EDIT

private bool itemSelected = false;

private void listBox1_SelectedItemChanged(object sender, EventArg e)
{
    if(itemSelected == false)
    {
        // select the item of listBox1
        itemSelected = true;
    }
    else
    {
        // Clear items of listBox2
        itemSelected = false;
    }
}

private void listBox2_SelectedItemChanged(object sender, EventArg e)
{
    if(itemSelected == false)
    {
         // select the item of listBox2
         itemSelected = true;
    }
    else
    {
          // Clear items of listBox1
          itemSelected = false;
    }
}

This code is not tested at all. So you might fix a bit the if-else condition

0
votes
listBox1.DataSource = new string[] { "AAAA", "BBBB", "CCCC", "DDDD", "EEEE" };
listBox2.DataSource = new string[] { "AAAA", "BBBB", "CCCC", "DDDD", "EEEE" };

// inline event handlers
listBox1.Click += (s,e)=>{
 listBox2.SelectedIndex = -1; 
};

listBox2.Click += (s,e) =>
{
 listBox1.SelectedIndex = -1; 
};

Regards.