Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

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:

 

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.
Can't afford to be neutral on a moving train...
  • *Experts*
Posted
Is it possible that the line:
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?

Posted

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.

Can't afford to be neutral on a moving train...
  • *Experts*
Posted

Just try putting

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{}.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...