views:

56

answers:

2

I'm trying to write to a data base, I have been working of the following site. In particular the LoadARow function.

I have been getting the runtime error

"System.IndexOutOfRangeException: A SqlCeParameter with ParameterName 'Value' is not contained by this SqlCeParamaterCollection.

The error references the line "command.Parameters["@Value"].Value = num;". The database I'm using has a Value column set as the key, and a text column.

using (SqlCeConnection connect = new SqlCeConnection("Data Source=C:\\Users\\mike\\Documents\\database.sdf"))
{
  connect.Open();

  string text = "test";
  int num = 0;

  using (SqlCeCommand command = new SqlCeCommand("insert into Data Table values (@Value, @Text)", connect))
  {
    command.Parameters.Add("@Text", SqlDbType.NVarChar);
    command.Parameters["@Value"].Value = num;
    command.Parameters.AddWithValue("@Text", text);
    command.ExecuteNonQuery();
  }
}
+1  A: 

The line:

command.Parameters.Add("@Text", SqlDbType.NVarChar); 

should read:

command.Parameters.Add("@Value", SqlDbType.NVarChar); 

You have not yet defined the variable at that point, which is why the next line errored out of index. A typo, I'm sure, since you defined @Text the line afterwards.

Fosco
+1  A: 

Try :

using (SqlCeConnection connect = new SqlCeConnection("Data Source=C:\\Users\\mike\\Documents\\database.sdf"))
    {
        connect.Open();

        string text = "test";
        int num = 0;

        using (SqlCeCommand command = new SqlCeCommand("insert into Data Table values (@Value, @Text)", connect))
        {
           command.Parameters.Add("@Value", SqlDbType.NVarChar, num);
           command.Parameters.Add("@Text", SqlDbType.NVarChar, text);
           command.ExecuteNonQuery();
        }
    }
mint
Thankyou for the fast replies. Both solutions took care of the error, but now I have "System.Data.SqlServerCe.SqlCeException: There was an error parsing the query. [Token line number = 1, Token line offset = 18]" at command.ExecuteNonQuery();
Mike
What is the name of your table? Your query should read "insert into [tablename] values...", so I'm guessing your table name is "Data_Table" and the query should be "insert into Data_Table values...". Also please accept whichever answer you like better using the check to the left of that answer.
Willfulwizard
The last problem ended up being a naming problem, table names seem to not be able to contain spaces, so changing it to Data_Table worked. Thankyou to everyone that helped.
Mike