Reputation: 6211
I have a listView that's pulling information from a MySql-server.
I'm currently using a timer
to update this information every 5 sec or so. But everytime updateListView
occurs, my selection loses focus. How would i prevent this? I've looked around on stackoverflow but i haven't been able to find a solution that works for me.
Here's my function updateListView
that i'm using (fetching data from mySql):
MySqlCommand cmd2 = new MySqlCommand("SELECT * FROM " + selectTable.Text, dbCon.Connection);
try
{
listView1.Items.Clear(); // suspecting that problem lies here,
// any other way to do this?
using (MySqlDataReader reader2 = cmd2.ExecuteReader())
{
while (reader2.Read())
{
ListViewItem item = new ListViewItem(reader2["ID"].ToString());
item.SubItems.Add(reader2["Name"].ToString());
item.SubItems.Add(reader2["Age"].ToString());
item.SubItems.Add(reader2["DiveNr"].ToString());
item.SubItems.Add(reader2["Difficulty"].ToString());
item.SubItems.Add(reader2["Points"].ToString());
listView1.Items.Add(item);
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error updateListView:" + ex.Message);
}
Upvotes: 0
Views: 31
Reputation: 54453
Since you have identifying IDs
in your data it will do to store the selected IDs
before clearing:
var sel = listView1.SelectedItems.Cast<ListViewItem>().Select(x => x.Name).ToList();
For the Find
to work it is best to set the Name
property of the ListViewItem
to hold those IDs
:
ListViewItem item = new ListViewItem(reader2["ID"].ToString());
item.Name = item.Text;
After the new data have been loaded you can then try to re-select each:
foreach (var lvi in sel)
{
var found = listView1.Items.Find(lvi, false);
if (found.Length > 0) found[0].Selected = true;
}
You may or may not want to try to reduce flicker during the update by SuspendLayout()
and ResumeLayout()
; ymmv..
Upvotes: 1