Gunnar Peipman's ASP.NET blog

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.

Comments

gt1329a said:

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

# July 19, 2008 8:57 AM

DigiMortal said:

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

# July 19, 2008 11:27 AM
Leave a Comment

(required) 

(required) 

(optional)

(required)