vignesh
vignesh

Reputation: 1

Index and length must refer to a location within the string. Parameter name: length exception

am getting the above exception while swaping Items in the list(lstRoutePriority).PFB my code

if (lstRoutePriority.SelectedIndex > 0)
{
   //Swap the two items 
   idTemp = (ItemData)lstRoutePriority.Items[lstRoutePriority.SelectedIndex];
   lstRoutePriority.Items[lstRoutePriority.SelectedIndex] = 
   lstRoutePriority.Items[lstRoutePriority.SelectedIndex-1];
   lstRoutePriority.Items[lstRoutePriority.SelectedIndex-1] = idTemp;
}

can someone tell me how to fix this? Thanks in advance

Upvotes: 0

Views: 2370

Answers (2)

Roy
Roy

Reputation: 44288

I think the

lstRoutePriority.SelectedIndex > 0

constraint is correct. Otherwise

lstRoutePriority.SelectedIndex-1

could be negative. I think you also should check whether SelectedIndex isn't larger than the length of the list minus 1.

Upvotes: 0

JAiro
JAiro

Reputation: 5999

Try replacing this

lstRoutePriority.SelectedIndex > 0 

by

lstRoutePriority.SelectedIndex >= 0

:)

Upvotes: 1

Related Questions