Hatem
Hatem

Reputation: 589

How to use SqlCeParameterCollection?

I wanna to know exactly how we do these thing on C# .NET 4.0 Form Application:

Here are samples of my current code:

Now how to add this collection at once to the command?

Thanks

Upvotes: 1

Views: 2013

Answers (2)

StuartLC
StuartLC

Reputation: 107267

SqlCeCommand.Parameters is read only, so you won't be able to assign a new SqlParametersCollection directly to this property.

You typically want to use the CreateCommand factory method on SqlCeConnection to create the command (as it will link the connection for you).

Then you use the command.Parameters directly:

SqlCeCommand cmd = con.CreateCommand();
// cmd.CommandType = ...; cmd.CommandText = ...
cmd.Parameters.Add("username", Username);
cmd.Parameters.Add("password", Password);

Upvotes: 1

marc_s
marc_s

Reputation: 754538

Try this:

string query = "...(whatever you need).....";

using(SqlCeConnection conn = new SqlCeConnection(connectionString))
using(SqlCeCommand cmd = new SqlCeCommand(query, conn))
{ 
    // just add parameters directly to SqlCeCommand object .... 
    cmd.Parameters.Add("username", Username);
    cmd.Parameters.Add("password", Password);

    conn.Open();
    cmd.ExecuteNonQuery();  // or whatever you need to do 
    conn.Close();
}

If you must set up your parameters separately, up front, then you need to do something like this (since you cannot directly use SqlCeParameterCollection):

List<SqlCeParameters> parameters = new List<SqlCeParameters>();

parameters.Add(new SqlCeParameter(.....));
parameters.Add(new SqlCeParameter(.....));

string query = "...(whatever you need).....";

using(SqlCeConnection conn = new SqlCeConnection(connectionString))
using(SqlCeCommand cmd = new SqlCeCommand(query, conn))
{ 
    // add all parameters from the list - casting to an array
    cmd.Parameters.AddRange(parameters.ToArray());

    conn.Open();
    cmd.ExecuteNonQuery();  // or whatever you need to do 
    conn.Close();
}

Upvotes: 3

Related Questions