Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Sending ASP.NET listbox values to Database

Status
Not open for further replies.

PM2000

Programmer
Aug 18, 2000
42
BM
Hi everyone,

I have a few multi-select list boxes on my asp.net page. The information needs to be sent back to the server to be stored in a database.

One list contains geographical regions:

North America
Europe
Africa
Asia

My code needs to convert this into a string to be sent to the DB. For example, if the user selects "Europe", the string "Europe" needs to go back. If they select Europe and Africa, then the string "Europe Africa" needs to go back. I have the following function that is supposed to create this string:

Private Function BuildListString(ByVal ctl As ListBox) As String
'Purpose
'Create a string from a multi-select list box

Dim str As String
Dim i As Integer

Try

'create the string
For i = 0 To ctl.Items.Count
If ctl.Items(i).Selected = True Then
If i = 0 Then
str = ctl.Items(i).Value
Else
str = str & " " & ctl.Items(i).Value
End If
End If
Next

Catch
End Try
End Function


The form has a few multi-select lists like the one described above, so I want to be able to pass the control to the function and re-use the code.

When I run the code, .net returns the error "Referenced object has a value of 'Nothing'."

Any ideas? Is it possible to do this?

Thanks
Peter
 
Try this:
At the top of your page:
Private _str as string

In your function:

_str = ""

For I = 0 To ctl.Items.Count - 1
If ctl.Items(I).Selected Then
If i = 0 Then
_str = ctl.Items(i).Value
Else
_str = _str & " " & ctl.Items(i).Value
End If
End If
Next

Hope this helps
 
A routine that concatenates selected strings in listboxes...

Dim s As String
Dim r As String
Dim i, n As Integer

'Make sure at least one Monitor is selected...or collect the various ones selected...

n = 0
If listContacts.SelectedIndex <> -1 Then
If listContacts.SelectionMode = ListSelectionMode.Single Then
Me.txtCN.Text = listContacts.SelectedItem.Text
Me.txtCID.Text = listContacts.SelectedItem.Value
Else
For i = listContacts.SelectedIndex To listContacts.Items.Count - 1
If listContacts.Items(i).Selected Then
n = n + 1
If n = 1 Then
s &= listContacts.Items(i).Text
r &= listContacts.Items(i).Value
Else
s &= &quot;, &quot; & listContacts.Items(i).Text
r &= &quot;, &quot; & listContacts.Items(i).Value
End If
End If
Next
Me.txtCN.Text = s
Me.txtCID.Text = r
End If
End If
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top