Defensive programming

At kmsystems we try to do as much defensive programming as possible when writing code. One of the most common is the use of "ElseIf" instead of just using "Else" in a If Then statement. Reason being is that it is a lot more specific and helps you really think about the scenarios you will be catching here.

Another one that should be just as common especially in ASP.NET is checking to see if an item already exists in a drop down list before selecting it. The problem here is if a item is programatically selected in a drop down list which doesn't exit the page will crash. This can occur when the user edits an existing record and the code attempts to bind the existing data to the form however the drop down list items may have changed and the item previously record here has changed or been removed.

Dim StrNot_In_List As Integer

StrNot_In_List = ddl_Control.Items.IndexOf(ddl_Control.Items.FindByValue(dr("db_Field"))

   If StrNot_In_List = -1 Then

      ddl_Control.Items.Add(New ListItem("db_Field", "db_Field"))

   End If

ddl_Control.SelectedIndex = ddl_Control.Items.IndexOf(ddl_Control.Items.FindByValue("db_Field"))

In the about code ddl_Control is the drop down list control and "db_Field" is the database field that needs to be selected in the drop down list.