locked
WPF ListBox Control - Get Selected Index of control Selected RRS feed

  • Question

  • I have  built a custom control that I programically  add to a List Box.  What I am looking to do is when a users selects (touch in the case of my app), they selected custom control is highlighted and then the app works with the data from that.  

    What I am not finding, is how to identify the selected index of the item within the List Box of the SelectionChanged event.  

    Can someone please point me in the right direction?

    Thanks,


    Robert Johnston

    Sunday, August 19, 2012 3:42 AM

Answers

  • Hi Robert,

    You use like this,

    private void listBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
            {
                //To get the Selected Index of the ListBox
                MessageBox.Show("The Selected Index is" + listBox1.SelectedIndex);
    
                //To get the selected ListItem
                ListBoxItem item = (ListBoxItem)listBox1.ItemContainerGenerator.ContainerFromIndex(listBox1.SelectedIndex);
            }

    Happy Programming!!!
    • Proposed as answer by Sheldon _Xiao Monday, August 20, 2012 8:24 AM
    • Marked as answer by Bob Johnston Monday, August 20, 2012 8:56 PM
    Sunday, August 19, 2012 1:35 PM

All replies

  • You should be able to use the SelectedIndex property of the ListBox.  

    http://msdn.microsoft.com/en-us/library/system.windows.controls.primitives.selector.selectedindex.aspx

    LS


    Lloyd Sheen


    • Edited by sqlguy Sunday, August 19, 2012 4:28 AM
    Sunday, August 19, 2012 4:27 AM
  • Hi Robert,

    You use like this,

    private void listBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
            {
                //To get the Selected Index of the ListBox
                MessageBox.Show("The Selected Index is" + listBox1.SelectedIndex);
    
                //To get the selected ListItem
                ListBoxItem item = (ListBoxItem)listBox1.ItemContainerGenerator.ContainerFromIndex(listBox1.SelectedIndex);
            }

    Happy Programming!!!
    • Proposed as answer by Sheldon _Xiao Monday, August 20, 2012 8:24 AM
    • Marked as answer by Bob Johnston Monday, August 20, 2012 8:56 PM
    Sunday, August 19, 2012 1:35 PM
  • This will works better...
    public void change(object sender, SelectionChangedEventArgs e)
            {
                // Get the currently selected item in the ListBox.
                string curItem = listBox1.SelectedIndex.ToString();
    
                // To show the selected item
                MessageBox.Show("You are selecting:" + curItem);
    
            }
    Feedback welcomed...
    • Proposed as answer by Sathi_NAGA Monday, August 20, 2012 5:36 AM
    • Unproposed as answer by Sathi_NAGA Monday, August 20, 2012 5:37 AM
    Monday, August 20, 2012 5:36 AM