Ok,
This is something that is usually one of those little annoying things that needs to be done… but you're never really sure the best way to do it. So here's the scenario:
You have a drop down list for "Courier". You bind the dropdownlist to a data source or other object with type IDataSource. The problem is what if they do not select a Courier. How do you record that they have none on file? Do you create an entry in the data source for an entry like "None"? Or do you have to add it to code?
I believe that the database should hold data that is used not take up space and cause more work… even if just a little for the data base server to have to sort through. So here is my solution: Add a few lines of code to create a "None" entry and handle it in the DB.
First you need to prep the database. For our example let's assume you have a table called couriers with the columns "CourierID", "Courier", and "Abbr". In your relational table where you will store the CourierID you need to make sure it is Nullable.
The second part is to add the code that will add the "None" entry to the Drop Down List.
Note: You can use the same procedure for other List Based Controls like the Radio Button List.
We use the "DataBound" event of the DropDownList because if we try to add our item before it has finished binding the "DataBinding" event will erase all of the entries we may have added. Use the code below:
Protected
Sub ddlOrgType_DataBound(ByVal sender As
Object, ByVal e As EventArgs)
Dim li As
New ListItem
li.Text = "None"
li.Value = ""
Me.ddlCouriers.Items.Insert(0, li)
End
Sub
So let's walk through the code… We create a list item. This allows us to specify the text, value, and all of the other properties of a list item. I have specified the text and value. The last step is to add the list item to the "Items" collection of the drop down list. We simply call the Insert method. The first overload specifies the index position for the list item to appear. I want mine to be the first in the list. The second overload is my list item.
Another option is to use the "Add" method but the list item will be placed at the end of the collection.
After this is done your extra list item will appear. Now when it is selected and saved back to the database the contents would be empty/null. You would need to add a display handler to write a label or string that said no courier is selected. Something like:
IF Contents = Nothing Then
'Throw Message
END IF
Of course the decision to do it like this is purely project based. I simply wanted to provide the process for keeping the logic in code versus the database for this instance.