ListBox.SelectedIndex

I have a listbox with it's selection mode set to multiextended. What I'm doing is catching the indexchanged event and displaying an image in a picturebox control. The problem I'm coming across is when multiple items are selected in the listbox. It seems that when the index is changed, even with multiple indices selected, the selectedindex contains the smallest index (i.e. if I select item at index 0 and then select item at index 5, selectedindex contains index 0). I know that there is also a selectedindices method, but I'm coming across the problem of finding out which was the last selected index. Basically, I would like my picturebox control to display the image in the last index selected. How would I go about doing something like this

Thanks,
Bill



Answer this question

ListBox.SelectedIndex

  • Luca_Dellamore - MS

    I don't want to get the highest index, I want to get the last index selected.

    If I select index 87, then index 3, then index 61, index 61 is the last index selected.


  • Andrew Whitechapel

     

    You can handle your SelectedValueChanged event of listbox to get the highest index that are selected in following way .

      private void listBox1_SelectedValueChanged(object sender, System.EventArgs e)
      {
         int indx = 0;
       for(int i =0;i<  ((ListBox)sender).Items.Count;i++)
       {
        if(this.((ListBox)sender).GetSelected(i))
        {
         indx = i;
        }
       }
       MessageBox.Show(indx.ToString());
      }

    This will always return u the highest index selected.



  • ListBox.SelectedIndex