Friday, March 9, 2012

query database user input from ListBox

I have a problem selecting fields from a table where fields are equal to user input from a listbox. example

listbox of zip codes:

33023
[red]22300[/red]
39844
[red]29339[/red]
23883
[red]38228[/red]

user wants to retreive highlight zip codes from database.
connection working perfect.
Thank you for your help.


you could use IN. check out books on line for more info.

SELECT

<columnlist>

FROM

yourtable

WHERE

zipcode IN ( ....)

|||

Hi There:

You need to retrieve the selected item from yous listbox first. Like this:

<code>

Dim sYourZipString As String = nothing
Dim sItem As ListItem
For Each sItem In zipListBox.Items
If sItem.Selected Then
sYourZipString = sYourZipString & "'" & sItem.Text & "', "
End If
Next

sYourZipString = sYourZipString.Remove(sYourZipString.Length-2, 2) ' remove the tail

</code>

You can use a select IN clause with a parameter which use the value(s) user.

Assume zipcode field is a text field (Char(5), or varchar(5) something not a number).


<code>
Dim conn As SqlConnection
Dim yourcmd As SqlCommand
Dim strConn as string = "yourconnection"

Dim yourSQLString As String
yourSQLString ="Select * FROM youTableIncludeZip WHERE zipcode IN (@.YourZipString)"

conn = New SqlConnection(strConn)

yourcmd = New SqlCommand(strUpdateStmt, conn)
yourcmd.Parameters.Add(New SQLParameter("@.Fname", txtFirstName.text))

Dim objDR as SQLDataReader
dim yourItem1fromDB as string =nothing
dim yourItem2fromDB as string =nothing
dim yourItem3fromDB as string =nothing

Try
conn.Open()
objDR=yourCmd.ExecuteReader(system.data.CommandBehavior.CloseConnection)

While objDR.Read()

yourItem1fromDB=objDR("yourItem1")
yourItem2fromDB=objDR("yourItem2")
yourItem3fromDB=objDR("yourItem3")
' ... get what you want from you Db table
End While

Finally
conn.close

End Try

</code>

Hope this help.


Limno

No comments:

Post a Comment