tags:

views:

41

answers:

4

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?

A: 

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
Kyra
That's pretty much what I'm doing (if you add " = true" on the end of your line). It does select the item, but it doesn't indicate anything to the user that the row is selected, which is my problem.
glaxaco
I used devExpress and all I you have to do there is change temp.Items(rowIndex).editValue = true.
Kyra
A: 

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.
    }
Bharath K
Why not use the built-in system highlighting?
Tony Abrams
This is what I did initially. It works, but it's definitely a suboptimal hack.
glaxaco
A: 

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.

Tony Abrams
That simply forces the control to have focus when the form is shown. If the user tabs off the control then the selection will again disappear.
gbogumil
Correct, since he is talking about having it selected when it's setup (IE: First displaying the control)
Tony Abrams
+2  A: 

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.

gbogumil
That was it; thank you! I knew it was something simple/stupid.
glaxaco
you're welcome.
gbogumil