AddWithValue Method

SqlParameterCollection.AddWithValue Method (String, Object)


Adds a value to the end of the SqlParameterCollection.

Namespace:   System.Data.SqlClient
Assembly:  System.Data (in System.Data.dll)

public SqlParameter AddWithValue(
	string parameterName,
	object value


Type: System.String

The name of the parameter.

Type: System.Object

The value to be added. Use DBNull.Value instead of null, to indicate a null value.

AddWithValue replaces the SqlParameterCollection.Add method that takes a String and an Object. The overload of Add that takes a string and an object was deprecated because of possible ambiguity with the SqlParameterCollection.Add overload that takes a String and a SqlDbType enumeration value where passing an integer with the string could be interpreted as being either the parameter value or the corresponding SqlDbType value. Use AddWithValue whenever you want to add a parameter by specifying its name and value.

For SqlDbTypeXml enumeration values, you can use a string, an XML value, an XmlReader derived type instance, or a SqlXml object.

The following example demonstrates how to use the AddWithValue method.

private static void UpdateDemographics(Int32 customerID,
    string demoXml, string connectionString)
    // Update the demographics for a store, which is stored 
    // in an xml column. 
    string commandText = "UPDATE Sales.Store SET Demographics = @demographics "
        + "WHERE CustomerID = @ID;";

    using (SqlConnection connection = new SqlConnection(connectionString))
        SqlCommand command = new SqlCommand(commandText, connection);
        command.Parameters.Add("@ID", SqlDbType.Int);
        command.Parameters["@ID"].Value = customerID;

        // Use AddWithValue to assign Demographics.
        // SQL Server will implicitly convert strings into XML.
        command.Parameters.AddWithValue("@demographics", demoXml);

            Int32 rowsAffected = command.ExecuteNonQuery();
            Console.WriteLine("RowsAffected: {0}", rowsAffected);
        catch (Exception ex)

.NET Framework
Available since 2.0
Return to top
© 2015 Microsoft