ListView.SelectedItems[0].Text Out of Range?

solus

Freshman
Joined
Apr 5, 2003
Location
Phoenix
So I have a ListView and I want to get the Selected Item's value and compare it to anothre string when the item is selected:

C#:
private void lstAccounts_SelectedIndexChanged(object sender, System.EventArgs e)
{
	XmlElement Root = this.XmlDoc["accounts"];

	foreach ( XmlElement account in Root.GetElementsByTagName( "account" ) )
	{
		if ( this.lstAccounts.SelectedItems[0].Text == account["username"].InnerText )
		{
			this.txtUsername.Text = account["username"].InnerText;
			this.txtPassword.Text = account["password"].InnerText;
			this.lstAccess.SelectedItem = account["accessLevel"].InnerText;
		}
	}
}

It works beautifully, but there's one probelm, it throws an exception if i click on the ListView a second time around and third and so on. It'll still do what it's supposed to, but throw an exception after the first time it's clicked on. What gives?

System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values.
 

Volte

Neutiquam Erro
Joined
Nov 17, 2002
Is it possible that the line:
C#:
this.lstAccess.SelectedItem = account["accessLevel"].InnerText;
Is trying to set the selected item to an item that doesn't exist within the listbox? Does the value of account["accesslevel"].InnerTextexist as an item within the textbox?
 

solus

Freshman
Joined
Apr 5, 2003
Location
Phoenix
Okay, best I can figure is at some point when you click an Item to select it, it's Selected Index is set to nothing. That would make ListView.SelectedItems[0] out of range. So to fix it i just surrounded it with a try{} and empty catch{}

Not sure if that's bad practice =p but i'll use it until some one can come up with a better suggestion.
 

Volte

Neutiquam Erro
Joined
Nov 17, 2002
Just try putting
C#:
if (this.lstAccounts.SelectedItems.Count > 0) {
  // the code that is in your event right now
}
That should be better than try..catch.

And no, there's nothing wrong with an empty catch{}.
 
Top Bottom