Advertise with us

C#: How to select the top item in a listview after sorting

I'm filling my System.Windows.Forms.ListView with results from my database as such:

foreach (DataRow row in theTable.Rows)

{

    ...build item from row..

    myListView.Items.Add(item);

}

And then I want to sort my listview in a different order than the rows come back from the DB, so I call

myListView.Sort();

But then when I want to go to select the top item in the listview it won't work, it selected something other than the top item:

myListView.Items[0].Selected = true;

Makes sense since the Items collection is added to in the order of the rows from the table iterated through in the foreach loop.

Using myListView.TopItem.Seleted = true doesn't work either.

So how do I go about selecting the topmost item in the listview AFTER I've sorted it?

Thanks for any answers.

Last updated:3/29/2014 7:11:51 AM

1 Answers

Pravesh Singh
Pravesh Singh

Hi Ben,

private void Populate(object sender, EventArgs e)
    {  
        listView1.Items.Add("D");
        listView1.Items.Add("B");
        listView1.Items.Add("A");
        listView1.Items.Add("C");
    }
    private void SelectFirst(object sender, EventArgs e)
    {
        listView1.Items[0].Selected = true;
        listView1.Select();
    }
    private void SortAndSelect(object sender, EventArgs e)
    {
        listView1.Sorting = SortOrder.Ascending;
        listView1.Sort();
        listView1.Items[0].Selected = true;
        listView1.Select();
    }

Answer