C #: how to select the top item in a list after sorting

I populate 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 list in a different order than the rows returned from the DB, so I call

 myListView.Sort(); 

But then, when I want to select the top item in the list, it will not work, it selected something different from the top item:

 myListView.Items[0].Selected = true; 

It makes sense because the Items collection is added in the order of the rows from the table that iterates through the foreach loop.

Using myListView.TopItem.Seleted = true does not work either.

So, how do I select the topmost item in the list? AFTER I sorted it?

Thanks for any answers.

+4
source share
2 answers

Are you sure the list is currently selected? If it is not selected, you will not see the item that will be selected.

The following code seems to work:

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

Pay attention to listView1.Select ()

+3
source

HideSelection is probably set to true. Make it false and try.

 myListView.HideSelection = false; 

In addition, lists may have a highlighted element, but do not focus on any other element. Therefore, it is better to set both focus and selection together:

 if (myListView.Items.Count > 0) { myListView.Items[0].Selected = true; myListView.Items[0].Focused = true; } 

If this does not work, you can set the focus to view the list to see if the selection hits the correct item.

+1
source

Source: https://habr.com/ru/post/1444953/


All Articles