PicoDeGallo
PicoDeGallo

Reputation: 608

"There was an error parsing the query. [Token line number = 1, Token line offset = 52,Token in error = Data]"

I am trying to select a set of data for a ComboBox based on the selection of the previous ComboBox. I have been lead to believe it is the SELECT statement in the second method, but I cannot figure out why it isn't working. When I run the application I receive this error: "There was an error parsing the query. [Token line number = 1, Token line offset = 52,Token in error = Data]" I have attempted using Parameter.AddWithValue, cmd.Parameters.Add, and also setting the value as a string to no avail. Would anyone mind teaching me how to correctly resolve this? Thank you.

The setup of the database is as follows:

Cities

Parks

Here is the method:

private void cboCities_SelectedIndexChanged(object sender, EventArgs e)
{
    if (cboCities.SelectedIndex > -1)
    {
        SqlCeConnection cn = new SqlCeConnection(@"Data Source = \Program Files\ParkSurvey\ParkSurvey.sdf; Persist Security Info = False; Password = *");
        cn.Open();
        SqlCeCommand cmd = cn.CreateCommand();
        cmd.CommandText = "SELECT Name FROM [Parks] WHERE CityId =" + cboCities.SelectedValue + "ORDER BY Name ASC";
        SqlCeDataAdapter da = new SqlCeDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);
        cn.Close();
        cboParks.ValueMember = "ParkId";
        cboParks.DisplayMember = "Name";
        cboParks.DataSource = ds.Tables[0];
        cboParks.SelectedIndex = -1;
    }

Upvotes: 1

Views: 3040

Answers (1)

Icarus
Icarus

Reputation: 63970

I know you mentioned that you tried parametrizing the query but if the error you are getting now is being thrown with the code you posted, then I would think it has to do with the fact that you are missing a blank space before "ORDER BY"; otherwise, the query executed will be something like:

SELECT Name FROM [Parks] WHERE CityId =5ORDER BY Name ASC;

Which is clearly invalid SQL.

Your query should be:

"SELECT Name FROM [Parks] WHERE CityId =" + cboCities.SelectedValue + " ORDER BY Name ASC";

With that being said, I'd look at parametrizing the query to avoid SQL Injection attacks. Using cmd.Paramters.AddWithValue is a better approach than writing this inline SQL statement.

Your query could be written then as:

"SELECT Name FROM [Parks] WHERE CityId = @CityID ORDER BY Name ASC";

And you can add the parameter as so:

cmd.Parameters.AddWithValue("@CityID",cboCities.SelectedValue);

Upvotes: 1

Related Questions