none
How to pass a comboBox value to an SQL query in c# RRS feed

  • Question

  • Hi,

    I would like to pass the value from my comboBox1 in a select statement, I know there are possible issues with SQL injection that I need to be wary of. My current code looks like this:

    "SELECT			*"+
    "FROM			dbo.destinations"+
    "WHERE			Name = comboBox1.Text"+ 
    "AND                    Dated =CONVERT (date, GETDATE( ) )"; 
    
    This code doesn't work because I don't know how to use the comboBox1 as a parameter in the query. How do I use the parameter in the query correctly and how can I make this injection proof?

    CuriousCoder

    Monday, April 9, 2018 3:20 PM

Answers

  • C# is not the same as SQL. 

    However, let us first take your SQL statement. 

    "SELECT	* FROM 	dbo.destinations WHERE Name = @1 AND  ...............

    And then you have somewhere a command related to your database you use and that needs a parameter

    cmd.Parameters.AddWithValue("@1",YourCombobox.SelectedItem)


    Success
    Cor


    Monday, April 9, 2018 3:33 PM

All replies

  • C# is not the same as SQL. 

    However, let us first take your SQL statement. 

    "SELECT	* FROM 	dbo.destinations WHERE Name = @1 AND  ...............

    And then you have somewhere a command related to your database you use and that needs a parameter

    cmd.Parameters.AddWithValue("@1",YourCombobox.SelectedItem)


    Success
    Cor


    Monday, April 9, 2018 3:33 PM
  • Thank you, that's great.

    CuriousCoder

    Monday, April 9, 2018 3:45 PM
  • If Cor solved the problem than you should mark his response as the answer.


    Sam Hobbs
    SimpleSamples.Info

    Monday, April 9, 2018 4:34 PM