Home > DeveloperSection > Forums > C#: How to select the top item in a listview after sorting
ben reitman
ben reitman

Total Post:96

Points:676
Posted on    March-29-2014 6:54 AM

 ASP.NET MVC ASP.NET MVC 
Ratings:


 1 Reply(s)
 2055  View(s)
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.



Pravesh Singh

Total Post:411

Points:2881
Posted on    March-29-2014 7:11 AM

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();

    }


Don't want to miss updates? Please click the below button!

Follow MindStick