Different way to pass parameter to command object in ASP.Net

Last Reply on Jul 02, 2016 05:58 AM By rani

Posted on Jul 01, 2016 03:48 AM

i have one table

fileds count 50

i am created the cmd.parameter.addwithvalue("",);

in 50 lines(fieldsname, datatype)

anyother alternate options avail pls send me. pls any example send me . 

regards

raja

Posted on Jul 02, 2016 05:58 AM Modified on on Jul 02, 2016 05:59 AM

These are the way to pass parameter to sql command.

using (SqlConnection conn = new SqlConnection(GetConnectionString())
{
    conn.Open();
    SqlCommand cmd = new SqlCommand(query, GetConnection());
    cmd.Parameters.Clear();
    //To add parameters refer any one below methods and execute query.

    //Method 1: Using AddWithValue function of SqlCommand parameter property.
    cmd.Parameters.AddWithValue("Fname", Value1);
    cmd.Parameters.AddWithValue("Lname", Value2);

    //Method 2: Using Add function of SqlCommand parameter property.
    SqlParameter paramFname = new SqlParameter();
    paramFname.ParameterName = "@Fname";
    paramFname.Value = Value1;
    cmd.Parameters.Add(paramFname);

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

    //Method 3: Using AddRange function of SqlCommand parameter property with array.
    SqlParameter[] SqlParameters = new SqlParameter[] 
        {
            new SqlParameter("@Fname", Value1),
            new SqlParameter("@Lname", Value2),
        };
    cmd.Parameters.AddRange(SqlParameters);

    //Method 4: Using AddRange function of SqlCommand parameter property with list.
    List<SqlParameter> list = new List<SqlParameter>();
    list.Add(new SqlParameter("@Fname", Value1));
    list.Add(new SqlParameter("@Lname", Value2));
    cmd.Parameters.AddRange(list.ToArray<SqlParameter>());

    SqlDataReader reader = cmd.ExecuteReader();
}