0

I am trying to get the value of selected item for my combobox which it loads the data from my database.

this is how i define the code. but I can't find what I'm missing. I get this error when i try to run the program.

private void LoadSchematicIndex()
{
   string sql;
      if (p2pMode == p2p.Trace)
         sql = string.Format("SELECT a.RecNo, a.FileName, 
         a.Title as [Trace Schematic Title] FROM Files a WHERE 
         a.ProjectRec = {0} AND a.SystemRec = {1} ORDER BY a.Title",
         (string)cbModel.SelectedValue, (int)systemMode);
}
Brian
  • 5,069
  • 7
  • 37
  • 47
V_H24
  • 129
  • 2
  • 10

1 Answers1

3

Probably your syntax error is due to the lack of single quote around the value for ProjectRec.
You should have written something like:

 "FROM Files a WHERE a.ProjectRec = '{0}' AND a.SystemRec = {1} ORDER BY a.Title"

But you should never use any form of string concatenation when building sql commands.
If you do, you expose your code to sql injection and you have to deal with parsing problems.

For example, strings should be enclosed in single quotations and, if a string value contains a single quote, you need to double it.

It is far better to use a parameterized query

    sql = "SELECT a.RecNo, a.FileName, a.Title as [Trace Schematic Title] " + 
          "FROM Files a WHERE a.ProjectRec = @prec AND a.SystemRec = @srec ORDER BY a.Title";

then, in your command or adapter

   SqlCommand cmd = new SqlCommand(sql, connection);
   cmd.Parameters.AddWithValue("@prec", cbModel.SelectedValue.ToString());
   cmd.Parameters.AddWithValue("@srec, systemMode);
Community
  • 1
  • 1
Steve
  • 213,761
  • 22
  • 232
  • 286