Like the others have said, the SelectedIndexChanged
event is what you should look at, however you should use it in collaboration with the ItemSelectionChanged
event. Here's some code I've just cooked up:
// Holds the last selected index
private int _previousIndex = -1;
// Restores the previous selection if there are no selections
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
if (listView1.SelectedIndices.Count == 0)
{
if (_previousIndex >= 0)
{
listView1.SelectedIndices.Add(_previousIndex);
}
}
}
// Records the last selected index
private void listView1_ItemSelectionChanged(object sender,
ListViewItemSelectionChangedEventArgs e)
{
if (e.IsSelected)
{
_previousIndex = e.ItemIndex;
}
}
For pure code re-use purposes, it'd probably be worthwhile putting this code into a new UserControl and have a property that determines whether or not to allow the last selection to be lost:
public class CustomListView : ListView
{
protected CustomListView()
{
this.SelectedIndexChanged += new EventHandler(CustomListView_SelectedIndexChanged);
this.ItemSelectionChanged += new ListViewItemSelectionChangedEventHandler(CustomListView_ItemSelectionChanged);
}
void CustomListView_SelectedIndexChanged(object sender, EventArgs e)
{
if (this.MaintainLastSelection && this.SelectedIndices.Count == 0)
{
if (_previousIndex >= 0)
{
this.SelectedIndices.Add(_previousIndex);
}
}
}
void CustomListView_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
{
if (e.IsSelected)
{
_previousIndex = e.ItemIndex;
}
}
private int _previousIndex = -1;
public bool MaintainLastSelection
{
get { return _maintainLastSelection; }
set { _maintainLastSelection = value; }
}
private bool _maintainLastSelection;
}