Eric Pohl
Eric Pohl

Reputation: 2344

Indicating a selected item in a listview

I have a ListView control in .NET Winforms containing filenames from a directory. When first displaying the control, I populate the listview, then programmatically select the first item in the list thusly:

    if (lvwFiles.Items.Count > 0)
    {
        ListViewItem firstItem = lvwFiles.Items[0];
        firstItem.Selected = true;
    }

This works fine, except that the first item in the list should be visually highlighted (reverse-highlighted?) to indicate to the user that it's the one selected, as happens if the user then clicks one of the items.

It seems like a dumb question, but I've looked around on Stackoverflow and elsehwere and don't see an obvious answer. Is there an easy way to make this happen via setting a property or something similar?

Upvotes: 1

Views: 272

Answers (4)

Greg Bogumil
Greg Bogumil

Reputation: 1923

Change the HideSelection property to false in the designer (or through code). Doing that will allow the selected item to show even when the control does not have focus.

Upvotes: 3

Tony Abrams
Tony Abrams

Reputation: 4673

What you are doing should work fine.

After a little testing it looks like the listview's tabstop property must be set to true, and the listview has to have a tab index of 0.

Upvotes: -1

Bharath K
Bharath K

Reputation: 2119

Register for the selectedIndexChanged event. Here you can perform whatever visual highlights you need on the selected items.

    void listView1_SelectedIndexChanged( object sender, EventArgs e )
    {
        foreach ( ListViewItem lvi in listView1.SelectedItems )
        {
            lvi.BackColor = Color.Black;
            lvi.ForeColor = Color.Chocolate;
        }
        // TODO: Reset the other items to normal.
    }

Upvotes: -1

Kyra
Kyra

Reputation: 5427

Not sure if this works as I haven't run the program but can't you select the row you want (from lvwFile.Items) and set the Selected value to true. For example:

temp.Items(rowIndex).Selected

Upvotes: 0

Related Questions