Milan
Milan

Reputation: 185

prevent item losing focus when refreshing list view in c#

I have list view and some columns "ID", "product name" and "Vendor". I can add, edit or delete those items and after "messing up" with items list view is refreshed something like this.

listView.Items.Clear();
foreach (var item in result)
{
    ListViewItem lv = new ListViewItem(item.ID.ToString());
    lv.SubItems.Add(item.Name.ToString());
    lv.SubItems.Add(item.Vendor.ToString());
    listView.Items.Add(lv);
}

so this method works fine except every time i refresh list focus of item is lost, which is logical because i deleted all items from list and filled it again. So my problem is how can i keep focus on edited and newly added items, primary when i edit some items i would like listview not to scroll to the top but to stay on place where that edited item was. I tried with method FindItemWithText and than setting focused items of listview to item that is found but it didn't work. Is there ant solution to this kind of problem?

Upvotes: 1

Views: 2273

Answers (1)

AgentFire
AgentFire

Reputation: 9780

Save focused item's index to the variable:

int oldFocusedIndex = listView.SelectedItems[0].Index;

Later then you can restore focus executing:

listView.Items[oldFocusedIndex].Selected = true;

You can also make the item visible to the user due to the ListView's scroll bar will remain at the top after the Clear() method:

listView.Items[oldFocusedIndex].EnsureVisible();

Upvotes: 5

Related Questions