SqlParameterCollection.AddWithValue Method (String, Object)


The .NET API Reference documentation has a new home. Visit the .NET API Browser on docs.microsoft.com to see the new experience.

Adds a value to the end of the SqlParameterCollection.

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

Public Function AddWithValue (
	parameterName As String,
	value As Object
) As SqlParameter


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 Sub UpdateDemographics(ByVal customerID As Integer, _
    ByVal demoXml As String, _
    ByVal connectionString As String)

    ' Update the demographics for a store, which is stored 
    ' in an xml column.
    Dim commandText As String = _
     "UPDATE Sales.Store SET Demographics = @demographics " _
     & "WHERE CustomerID = @ID;"

    Using connection As New SqlConnection(connectionString)
        Dim command As New SqlCommand(commandText, connection)

        ' Add CustomerID parameter for WHERE clause.
        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)

            Dim rowsAffected As Integer = command.ExecuteNonQuery()
            Console.WriteLine("RowsAffected: {0}", rowsAffected)

        Catch ex As Exception
        End Try
    End Using
End Sub

.NET Framework
Available since 2.0
Return to top