0

I have a DataTable. How to set a certain value of it as one of my SqlParameters? I receive this error message: The SqlParameterCollection only accepts non-null SqlParameter type objects, not String objects.

Either I do:

myCommand.Parameters.Add("@managedBy");
myCommand.Parameters["@managedBy"].Value = comp.Rows[i][4].ToString();

myCommand.Parameters.Add("@modified_at");
myCommand.Parameters["@modified_at"].Value = DateTime.Now.ToString("MM/dd/yyyy");

myCommand.Parameters.Add("@cn");
myCommand.Parameters["@cn"].Value = comp.Rows[i][1].ToString();

or:

myCommand.Parameters.Add("@managedBy");
myCommand.Parameters["@managedBy"].Value = (SqlParameter)comp.Rows[i][4];

myCommand.Parameters.Add("@modified_at");
myCommand.Parameters["@modified_at"].Value = DateTime.Now.ToString("MM/dd/yyyy");

myCommand.Parameters.Add("@cn");
myCommand.Parameters["@cn"].Value = (SqlParameter)comp.Rows[i][1];

What am I missing? How to set the parameter from a DataTable?

0

3 Answers 3

1

The SqlParameterCollection.Add method overloads with one argument requires that the argument be a SqlParameter. To create an argument with a string name you also need to specify the type (and optionally a size):

myCommand.Parameters.Add("@managedBy", SqlDbType.NVarChar);

To set the value in one call you can use AddWithValue, wihch will infer the SQL type from the value type:

myCommand.Parameters.AddWithValue("@managedBy", comp.Rows[i][4]);
Sign up to request clarification or add additional context in comments.

Comments

1

The SqlParametersCollection inside the SqlCommand object has an Add method that wants an SqlParameter object.

So your code should be something like this

 myCommand.Parameters.Add(new SqlCommand("@managedBy", SqlDbType.AnsiString)).Value = .......;

There are numerous possibilities to add a new parameter to the collection, the easiest of which is

 myCommand.Parameters.AddWithValue("@managedBy", comp.Rows[i][4].ToString());

This particular version however requires particular care as explained in this very detailed article on MSDN

Comments

0

Use the following code:

myCommand.Parameters.AddWithValue("ParameterName", anyObject);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.