Connect SqlParameterCollection to SqlCommand

T

tshad

I have to pass a parameter collection to a method and then add it to the
SqlCommand.

Can I do that without having to go throught a foreach loop?

I tried to do :

command.Parameters = sqlParams;

where sqlParams is an SqlParameterCollection.

But got a message saying that it was readonly.

I can loop through and just do:

if (sqlParams != null)
foreach(SqlParameter param in sqlParams)
dbCommand.Parameters.Add(param);

But was curious if I can just attach the collection?

Thanks,

Tom
 
C

Chris Dunaway

I have to pass a parameter collection to a method and then add it to the
SqlCommand.

Can I do that without having to go throught a foreach loop?

I tried to do :

command.Parameters = sqlParams;

where sqlParams is an SqlParameterCollection.

But got a message saying that it was readonly.

I can loop through and just do:

if (sqlParams != null)
foreach(SqlParameter param in sqlParams)
dbCommand.Parameters.Add(param);

But was curious if I can just attach the collection?

Thanks,

Tom

The SqlParameterCollection object has an AddRange method. Perhaps you
could just add all of them in one line:

dbCommand.Parameters.AddRange(sqlParams)

I'm not sure if this will work, however.

Chris
 
T

tshad

I did find out that you can't directly instantiate the
SqlParameterCollection class, so I created a List<SqlParameter> to do the
same thing.

(actually you do: SqlParameterCollection params = new
SqlCommand.Parameters;)

I do the same foreach code below and it works fine.

But I can't seem to create the collection and pass it in the same line. So
I changed my code to do:

List<SqlParameter> sqlParams = new List<SqlParameter>();
sqlParams.Add(new
SqlParameter("ClientID",Convert.ToInt32(ddlClient.SelectedItem.Value)));

DataAccess.GetDropDown(lcJob, "GetJobNumbers", "JobNumber",
"JobId", sqlParams);

I also tried to pass it in one line
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top