Avoiding exceptions using list controls

Avoiding excpetions is always a good practice because exceptions can hurt as when thay occure. They may cause also hard performance loss. Assigning selected value to list controls is one candidate for ArgumentOutOfRange exceptions.

Often this problem is solved using unhandled exception:


try 
{
    cboServiceGroup.SelectedValue = group.Id.ToString();
}

catch { ; }

To avoid this exception we can check out if value exists in list before we assign it to list control.


if (cboServiceGroup.Items.FindByValue(group.Id.ToString()) != null) 
{
    cboServiceGroup.SelectedValue = group.Id.ToString();
}

This way we will avoid a lot of exceptions in our code when we are writing user interfaces where lists are widely used.


4 thoughts on “Avoiding exceptions using list controls

Leave a Reply

Your email address will not be published. Required fields are marked *