New to .net question

I am learning .net from a book, so will probably be asking many questions on here in the coming months! Here is the first:

To create an output parameter to send to procedure in order to return the id of the new record the book uses:


cmdSql.Parameters.Add(new SqlParameter("@ID", SqlDbType.Int, 4));
cmdSql.Parameters["@ID"].Direction = ParameterDirection.Output;

It also states that the short method of adding params is:

cmdSql.Parameters.AddWithValue("@Param1", "Test");

but states this cannot be used for output params, so i did this:


cmdSql.Parameters.Add("@ID", SqlDbType.Int, 4);
cmdSql.Parameters["@ID"].Direction = ParameterDirection.Output;

Is there anything wrong with not declaring the new sqlParameter within the add method?

cheers

monkey

This is what I use.


SqlConnection connection = new SqlConnection(connectionString);
 
   // Command - specify as StoredProcedure
   SqlCommand command = new SqlCommand(storedProcedureName, connection);
   command.CommandType = CommandType.StoredProcedure;
 
   // Return value as parameter
   SqlParameter returnValue = new SqlParameter("returnVal", SqlDbType.Int);
   returnValue.Value="TextBox1.Text"; 
   returnValue.Direction = ParameterDirection.ReturnValue;
   command.Parameters.Add(returnValue);
 
    // Execute the stored procedure
   connection.Open();
   command.ExecuteNonQuery();
   connection.Close();
 
   return Convert.ToInt32(returnValue.Value);

Note: I edited the code.

Cheers. That seems more long winded - what is the benefit of doing it this way?

cheers

That’s the beauty. You can do your solution 1,000 different ways. This is just how I do it. You could avoid the SQLParameter variable all together, and just add it to the Command object like you did.

There is no benefit other than having ur code a bit more readable. Which is always a win in my book

Thanks all - I learnt asp in a very backwards way, so want to learn .net the best way from the off, so standards and best practice are at the forefront of my learning!

Cheers