Mike
Mike

Reputation: 3

SQL CE 3.5 - Writing to a database

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();
  }
}

Upvotes: 0

Views: 4068

Answers (2)

mint
mint

Reputation: 3433

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();
        }
    }

Upvotes: 2

Fosco
Fosco

Reputation: 38526

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.

Upvotes: 1

Related Questions