0

I am making page to display information from table (Like inbox page of any email website). But I am gettting the following error:

Incorrect syntax near the keyword 'to'.

Below is my C# code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

public partial class Inbox : System.Web.UI.Page
{
SqlConnection con = new SqlConnection();
SqlCommand cmmd = new SqlCommand();
protected void Page_Load(object sender, EventArgs e)
{
    con.ConnectionString=@"Data Source=(LocalDB)\v11.0;AttachDbFilename=c:\Users\user\documents\visual studio 2012\WebSites\Email\App_Data\Database.mdf;Integrated Security=True";
    con.Open();
    label1.Text = Session["uid"].ToString();

    cmmd.CommandText = "select frm from Inbox where to='" + Session["uid2"].ToString() + "'";
    cmmd.Connection= con;
    SqlDataAdapter daa = new SqlDataAdapter(cmmd);
    DataTable dtt = new DataTable();
    daa.Fill(dtt);

    if(dtt.Rows.Count > 0)
    {
        label2.Text = dtt.Rows[0][3].ToString();
    }

}

}

How to Solve this error?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Jignesh M. Khatri
  • 1,407
  • 1
  • 14
  • 22
  • i assume it refers to the line `cmmd.CommandText = "select frm...`, did you try adding a `@` in front of the string ? – Banana Jul 12 '14 at 13:02
  • Also, make sure you read [this](http://stackoverflow.com/q/541620/21567) and related material. – Christian.K Jul 12 '14 at 13:27

1 Answers1

5

Use "[to]" instead of just "to". It is problem when you use reserved term for field name.

It should be like this:

cmmd.CommandText = "select [frm] from [Inbox] where [to]='" + Session["uid2"].ToString() + "'";

EDIT:

And yes, for better security and less error-prone code you should use SqlParameter, something like that:

cmmd.CommandText = "select [frm] from [Inbox] where [to]=@SID"
cmmd.Parameters.Add("@SID", SqlDbType.Varchar);
cmmd.Parameters["@SID"].Value = Session["uid"].ToString();;
Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
Vojtěch Dohnal
  • 7,867
  • 3
  • 43
  • 105