# 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”

• gt1329a says:

It would be interesting though, to see the actual performance difference between handling the occasional exception and executing FindByValue on every single operation.

• Gunnar says:

Exceptions may be much more ressource eager than those FindByValue calls. Normally you don’t have long dropdownlists by example.

• Very elegant solution, using correclty the concepts of .NET. Thanks.