Different ways of passing/adding SqlParameter to SqlCommand parameter property in ADO.NET C#

By Mash B

Different ways of passing SqlParameter to SqlCommand parameter property.

Ex.

using (SqlConnection conn = new SqlConnection("Your conn string"))
{
conn.Open();

string selectQuery = "Select * FROM Person where Fname=@Fname and Lname=@Lname";

using (SqlCommand cmd = new SqlCommand(selectQuery, conn))
{
        // To add parameters refer any one below methods  and execute query
SqlDataReader reader = cmd.ExecuteReader();
}
}

Method
1:
// Using AddWithValue function of SqlCommand parameter property

cmd.Parameters.AddWithValue("Fname", "Your Value");
cmd.Parameters.AddWithValue("Lname", "Your Value");


Method
2:
// Using Add function of SqlCommand parameter property

SqlParameter
paramFname = new SqlParameter();
paramFname.ParameterName = "@Fname";
paramFname.Value = "Your Value";
cmd.Parameters.Add(paramFname);

SqlParameter
paramLname = new SqlParameter();
paramLname.ParameterName = "@Lname";
paramLname.Value = "Your Value";
cmd.Parameters.Add(paramLname);

Method
3:
// using AddRange function of SqlCommand parameter property

SqlParameter[] SqlParameters = new SqlParameter[] {
                                                     new SqlParameter("@Fname", SqlDbType.VarChar, 100),
                                                      new SqlParameter("@Lname", SqlDbType.VarChar, 100),
                                                 };
cmd.Parameters.AddRange(SqlParameters);

Different ways of passing/adding SqlParameter to SqlCommand parameter property in ADO.NET C#  (5024 Views)