Using Visual Studio 2008, .Net 3.5
I have a ListView loaded with a bunch of items. I have a right-click popup for removing an item. After removal of an item, I redraw the list view by re-accessing my primary data, and reset the selected item. However, the selected item does not show as selected.
An idea of the code:
public ListView m_lv;
public MyDataCollection m_Data; // Has a function to get data based on a tag.
public void RemoveEventHandler(object sender, EventArgs e)
{
int iSelectedItem= m_lv.FocusedItem.Index;
int iDataIndexToRemove= m_Data.GetIndexOf(m_lv.FocusedItem.Tag.ToString());
m_Data.RemoveAt(iDataIndexToRemove); // Remove the item.
if(0 != m_lv.Items.Count)
{
if(iSelectedItem == m_Data.Items.Count) // Removed last.
iSelectedItem= m_Data.Items.Count - 1;
}
m_lv.Items.Clear(); // Clear the list view items.
// Completely rebuild the list view.
foreach(MyData md in m_Data)
{
ListViewItem lvi= new ListViewItem(md.Column0.ToString());
lvi.SubItems.Add(md.Column1.ToString());
lvi.SubItems.Add(md.Column3.ToString());
lvi.SubItems.Add(md.Column4.ToString());
m_lv.Items.Add(lvi);
}
// Set up tags, column sizes, etc.
if(0 != m_lv.Items.Count)
m_lv.Items[iSelectedItem].Selected= true; // Set the selection.
}
If I do something like the above, the selected item never shows visually as selected (no background color change) unless I re-size a column or sort. Then it shows as selected. However, if I use the debugger or add a button to use a message box to show me selected items, the item knows it is selected.
I know it is some kind of refresh/drawing problem - any ideas?