#979 – Selecting Items in a ListBox Programmatically

The ListBoxItem object, representing a single item in a ListBox, contains an IsSelected property that you can read in order to determine whether the item is selected.  The IsSelected property can be read from to determine if the item is selected.  It can also be written to, to select the item.

The code below selects every other item in a ListBox.  Note that we need to call the ItemContainerGenerator.ContainerFromIndex helper method in order to get the ListBoxItem for each item.

private void btnWrite_Click(object sender, RoutedEventArgs e)
{
    // Select every other item, starting with
    // the first.
    int i = 0;
    while (i < lbActors.Items.Count)
    {
        // Get item's ListBoxItem
        ListBoxItem lbi = (ListBoxItem)lbActors.ItemContainerGenerator.ContainerFromIndex(i);
        lbi.IsSelected = true;
        i += 2;
    }
}

979-001

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

4 Responses to #979 – Selecting Items in a ListBox Programmatically

  1. Pingback: Dew Drop – January 3, 2014 (#1694) | Morning Dew

  2. Per Eriksson says:

    Great post!!! One line of code to solve a problem that all other sites suggest can only be solved with template changes etc etc

  3. Alex says:

    Hi Sean, for some reason while the code is going through the items are not actually shown as selected in the ListBox. I’m trying it with different events such as control load and even button click. Please, advise if you might know what could be the cause of it.
    Thanks,
    Alex

    • Sean says:

      Hi Alex,

      It’s hard to know what’s going on without seeing your code. Note that in almost all cases you’ll want to select items in a ListBox using data binding, rather than programatically. The technique presented in WPF isn’t really the preferred way to do it. Much cleaner is the technique shown in post #980, using data binding to do the same thing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: