Inserting multiple listbox items into SQL with ASP.NET
I ran into my first, of what will surely become many, hurdles while programming my new weblog. How to insert multiple listbox selections into a SQL database (like multiple categories for an individual weblog entry). At first it seemed simple, but then none of the examples would work properly. I started with this code:
Dim oItem as ListItemFor each oItem in oListBox.Items If oItem.Selected Then [insert oItem.value into SQL database] End IfNext
But this wouldn’t work! After fooling around with the code I managed to insert all list items (regardless of selection status) which told me that the problem lie in the “If” statement. I could not for the life of me figure this out. I searched and I searched Google for the answer, but to no avail. Finally, after hours of frustration, I reached a newsgroup post that was on a related topic. It turns out that the problem stems from the listbox being changed on PostBack from the server. So simply wrapping the code that creates the listbox in the first place with a
If not Page.IsPostBack [create list box]End If
solved the problem. After figuring this out, it made perfect sense to me. That is how all of these problems end up (assuming I find the answer), always something simple.