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 bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

SELECT statement based on user input

Status
Not open for further replies.

Charlix

Programmer
Nov 19, 2002
85
US
I have a relational database that has several fields in it (color, product, format, type, etc). I want the user to be able to identify products based on the defect, format etc. I can write an SQL statement that gets the products if I specify the color programmatically. For example,

SELECT [Product] FROM [Table1] WHERE [Color] = ‘Red’

This gives the user all the products that have a red color. But, if I use a drop down list (e.g.,a dropdown list named ddColor) and let the user select the color the code doesn’t work. This doesn’t work

SELECT [Product] FROM [Table1] where [Color] = ‘ ddColor.SelectedValue’.

I know this is a trivial problem but I can’t do it. Where do I go to get some help?
 
what is the error you're getting? Are you sure you have the correct value from the drop down?
 
The color column's datatype ??

Set the ddl's autopostback to true, and send the query in the ddl's selected index changed event handler.
 
check that ddColor.SelectedValue is returning ur desired value or not

may be ur dropdownlist has text as 'red', 'green', 'blue' etc ... but the value wud be like 0, 1, 2 etc... or some thing else

y dont u try

ddColor.SelectedItem.Text


Regards,
Rashida Jabeen
 
I presume you are doing this programmatically... If you create the query within the ddl method, it could look something like this:
"SELECT [Product] FROM [Table1] where [Color] = ‘" + ddColor.SelectedValue +"’".

Notice that I separated the ddl property from the SQL string. When it compiles, it reads as :
SELECT [Product] FROM [Table1] where [Color] = '[Color]'.

Hope this works for you.
 
"SELECT [Product] FROM [Table1] where [Color] = ‘" + ddColor.SelectedValue +"’"

This is a step in the right direction, but you never want to do something like this because of the threat of SQL injection (a HUGE vulnerability).


Better to do something like this:

Code:
Dim sql AS String = "SELECT [Product] FROM [Table1] where [Color] = @Parameter"

Dim cmd AS DbCommand = new SqlCommand( sql )
Dim colorVal As DbParameter = cmd.CreateParameter()
colorVal.ParameterName = "@Parameter"
colorVal.Value = ddColor.SelectedValue
cmd.Parameters.Add(colorVal)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top