0

I made a button to receive the texts from two combo boxes. The connection is OK and the names in the combo box too, but when I run the application for any two valid names I receive the message Invalid column name. I'm sure that the column names are valid according to my data base.

Here's my code:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnProcesar.Click

  sql.sqlcon.Open()
  sql.sqlsentence = New SqlCommand("SELECT * FROM dbo.Univ$ WHERE Sector =  " & ingSector.Text & "  AND Ciudad =  " & ingCiudad.Text, sql.sqlcon)

  Dim adaptador As SqlDataAdapter
  adaptador = New SqlDataAdapter(sql.sqlsentence)

  Dim ds As New DataSet
  adaptador.Fill(ds)
  sql.sqlcon.Close()
  dgrid.DataSource = ds.Tables(0)

End Sub

So, how can I fix that?

2

2 Answers 2

4

Do this instead of your current one to avoid SQL injection.

  Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnProcesar.Click
    sql.sqlcon.Open()
    sql.sqlsentence = New SqlCommand("SELECT * FROM dbo.Univ$ WHERE Sector=@sector AND Ciudad=@ciudad" , sql.sqlcon)

    Dim adaptador As SqlDataAdapter
    adaptador = New SqlDataAdapter(sql.sqlsentence)
    adaptador.SelectCommand.Parameters.AddWithValue("@sector", ingSector.Text)
    adaptador.SelectCommand.Parameters.AddWithValue("@ciudad", ingCiudad.Text)

    Dim ds As New DataSet
    adaptador.Fill(ds)
    Sql.sqlcon.Close()
    dgrid.DataSource = ds.Tables(0)
  End Sub
Sign up to request clarification or add additional context in comments.

Comments

3

You don't have apostrophes around the string literals in the query, so the database thinks that the values are supposed to be column names.

Adding apostrophes around the values would make it work:

sql.sqlsentence = New SqlCommand("SELECT * FROM dbo.Univ$ WHERE Sector =  '" & ingSector.Text & "'  AND Ciudad =  '" & ingCiudad.Text & "'", sql.sqlcon)

However, you should really look into using a parameterised query to use the values, instead of concatenating the values into the query.

2 Comments

Thanks for making that clear !. Why Should I look into using a parameterised query? Would you mind recommending a goord resource about that topic?
This will get you started. software-security.sans.org/developer-how-to/…. While the focus is on security, I think the biggest values are escaping special characters, like apostrophes, and better performance.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.