C#: HOW TO SELECT THE TOP ITEM IN A LISTVIEW AFTER SORTING

ben reitman

Total Post:96

Points:676
Posted by  ben reitman
 2658  View(s)
Ratings:
Rate this:

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.

  1. Pravesh Singh

    Post:412

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

    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

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!