1

I am trying to select item in ListBox in program, but I was so far unable to do so.

I looked for the answer but everything I found was to use ListBox.SetSelected() method, but I don't have anything like that awaiable.

I discovered that there are two completely different ListBoxes and I am using the second one:

System.Windows.Forms.ListBox
System.Windows.Controls.ListBox

All items in the ListBox are added via Binding, which doesn't help either. Any ideas?

EDIT :

I just found that this works:

listBox.SelectedIndex = 5;
listBox.UpdateLayout();
listBox.Focus();

Apparently, I was missing the last method, which sets the highlight to the selected item, which was updating fine even before.

1
  • can you please show some more code including what you have tried in order to set the selected item in the listbox? Commented Feb 16, 2017 at 13:53

4 Answers 4

2

have you tried SelectedItem.

example:

private void listBox1_SelectedIndexChanged(object sender, System.EventArgs e)
{
   // Get the currently selected item in the ListBox.
   string curItem = listBox1.SelectedItem.ToString();

}
Sign up to request clarification or add additional context in comments.

Comments

2

Here is the documentation from the MSDN site on setting the selected item in a listbox. Here it is being done on a button click event.

private void button1_Click(object sender, System.EventArgs e)
{
    listBox1.Items.Add("One");
    listBox1.Items.Add("Two");
    listBox1.Items.Add("Three");
    listBox1.SelectedIndex = listBox1.FindString("Two");
}

1 Comment

Well thanx, but this one is from System.Windows.Forms.ListBox which I am not using. There is no FindString()...
1

Have you tried setting it via the SelectedIndex https://msdn.microsoft.com/en-gb/library/system.windows.controls.primitives.selector.selectedindex(v=vs.110).aspx or the SelectedItem https://msdn.microsoft.com/en-gb/library/system.windows.controls.primitives.selector.selecteditem(v=vs.110).aspx or SelectedItems (for multiple selection) https://msdn.microsoft.com/en-gb/library/system.windows.controls.listbox.selecteditems(v=vs.110).aspx ?

1 Comment

Sure, I've tried all three. They will select item, but they won't highlight it. You apparently need .UpdateLayout() and most importantly .Focus() after that...
0

To get the currently selected item use

ListBox.SelectedItems()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.