Wednesday, March 21, 2012

grabbing a value from listbox to query database

hello forum,

I need to grab astring value from alist box in from a web form,
and pass it to a sql select command statement where that value is equal to
all values in a database table(sql 2000).

example

zip code list box
33154
33254
84578
85475
35454

selected value is 85475

I am putting that value in a string like this:

dim string_zip as string
string_zip = zip_ListBox.text

Question, how do i pass that value to sql stament, i am using this but does not work.

SqlCommand1 =New SqlCommand("SELECT zip FROM table WHERE zip =string_zip", SqlConnection1)

You should use this

SqlCommand1 =New SqlCommand("SELECT zip FROM table WHERE zip ='" &string_zip &"'", SqlConnection1)

Regards

|||

Actually, you should use this:

SqlCommand1=new sqlcommand("SELECT zip FROM table WHERE zip=@.zip",SqlConnection1)
SqlCommand1.parameters.add(new sqlparameter("@.zip",sqldbtype.varchar))
SqlCommand1.parameters("@.zip").value=string_zip

Using the string concatenation method is a good way to get yourself hacked.

|||

Motley wrote:

Actually, you should use this:

SqlCommand1=new sqlcommand("SELECT zip FROM table WHERE zip=@.zip",SqlConnection1)
SqlCommand1.parameters.add(new sqlparameter("@.zip",sqldbtype.varchar))
SqlCommand1.parameters("@.zip").value=string_zip

Using the string concatenation method is a good way to get yourself hacked.

Yes, this is preferred over my solution becuase it is more secure.

Thanks Motley

|||

Thanks for you help, it works, but I encounter another problem.

Problem:

multiple selection from list box is allowed, I am getting a string value from all selected choices like this:

Dim listofstringsAsString
Dim itemAs ListItem

ForEach itemIn listbox.Items
If item.SelectedThen
listofstrings = listofstrings & item.Text & ","
EndIf
Next

so i havelistofstrings = (selectedvalue1,selectedvalue2,selectedvalue3,......)

I need to select all values from a table in database where any of those values corresponds.

NOTE: Values in database can also be in the format of (value1,value2,value3,.....) or just a single (value1,)

|||

Search for messages on the UDF named "Split" one was posted recently.

SELECT *
FROM table
WHERE field IN (SELECT * FROM Split(@.listofstrings))

OR
SELECT *
FROM table
JOIN Split(@.listofstrings) s ON (table.field=s.id)

No comments:

Post a Comment