2

I am getting this error

Incorrect syntax near "="

I am getting this error on the line

sda.Fill(dt); 

I can't figure out what mistake I have made. I went through many articles but none of them can help me with my problem.

SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\TECHNOGEEKZ\Desktop\USSv0.1\USSv0.1\USSv0.1\db\Database.mdf;Integrated Security=True");

con.Open();

SqlDataAdapter sda = new SqlDataAdapter("SELECT name FROM attachments WHERE idno = " + comboBox1.Text + "", con);

DataTable dt = new DataTable();
sda.Fill(dt);

comboBox2.DataSource = dt;
comboBox2.DisplayMember = "name";
comboBox2.ValueMember = "name";

Database table looks like

CREATE TABLE [dbo].[attachments] 
(
    [Id]       INT           IDENTITY (1, 1) NOT NULL,
    [idno]     INT           NULL,
    [name]     VARCHAR (MAX) NULL,
    [location] VARCHAR (MAX) NULL
);

Can somebody solve this error? Where exactly is the error in this code?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Ashwini Nemade
  • 153
  • 1
  • 13
  • 1
    I think comboBox1.Text is an empty sting. – PepitoSh Jun 22 '18 at 05:37
  • @PepitoSh Yes it was empty I just checked.. Thanks a lot it helped!! – Ashwini Nemade Jun 22 '18 at 05:39
  • 1
    [SQL Injection alert](http://msdn.microsoft.com/en-us/library/ms161953%28v=sql.105%29.aspx) - you should **not** concatenate together your SQL statements - use **parametrized queries** instead to avoid SQL injection - check out [Little Bobby Tables](http://bobby-tables.com/) – marc_s Jun 22 '18 at 07:15

1 Answers1

4

First, try to return comboBox1.Text, to see whether which value it returns. Let say it returns a empty, null value or not an integer number, your query will be wrong.

Second, instead of passing directly comboBox1.Text to your SQL query, you should use parameter.

It helps to reduce ridiculous error like you have currently, as well as preventing SQL injection.

Change your sda to:

SqlDataAdapter sda = new SqlDataAdapter("SELECT name FROM attachments WHERE idno = @idNo", con);

sda.SelectCommand.Parameters.AddWithValue("@idNo",comboBox1.Text);
Jacky
  • 2,924
  • 3
  • 22
  • 34