A flag works for the OnLoad event of the windows form / web form / mobile form.
In a single select Listview, not multi-select, the following code is simple to implement, and prevents multiple firing of the event.
As the ListView de-selects the first item, the second item it what you need and the collection should only ever contain one item.
The same below was used in a mobile application, therefore some of the collection names might be different as it is using the compact framework, however the same principles apply.
Note: Make sure OnLoad and populate of the listview you set the first item to be selected.
// ################ CODE STARTS HERE ################
//Flag to create at the form level
System.Boolean lsvLoadFlag = true;
//Make sure to set the flag to true at the begin of the form load and after
private void frmMain_Load(object sender, EventArgs e)
{
//Prevent the listview from firing crazy in a single click NOT multislect environment
lsvLoadFlag = true;
//DO SOME CODE....
//Enable the listview to process events
lsvLoadFlag = false;
}
//Populate First then this line of code
lsvMain.Items[0].Selected = true;
//SelectedIndexChanged Event
private void lsvMain_SelectedIndexChanged(object sender, EventArgs e)
{
ListViewItem lvi = null;
if (!lsvLoadFlag)
{
if (this.lsvMain.SelectedIndices != null)
{
if (this.lsvMain.SelectedIndices.Count == 1)
{
lvi = this.lsvMain.Items[this.lsvMain.SelectedIndices[0]];
}
}
}
}
################ CODE END HERE ################
Ideally, this code should be put into a UserControl for easy re-use and distrbution in a single select ListView. This code would not be much use in a multi-select, as the event works as it should for that behavior.
I hope that helps.
Kind regards,
Anthony N. Urwin
http://www.manatix.com