Fabian
Fabian

Reputation: 289

How to keep SQL tble field not updated when I update other fields in Visual Basic?

I have a class that allows me to update the sql table field. One of the fields that I want to update is the file name. The following function returns the file name based on some conditions. The problem that I am having is the else clause.

Public Function checkFileNamesForUpdate(ByVal file As FileUpload, ByVal firstName As String, ByVal lastName As String, ByVal text As String, ByVal hyper As HyperLink) As String
    If (file.HasFile) Then
        Return firstName.ToLower + "_" + lastName.ToLower + "_" + text
    ElseIf (Not file.HasFile AndAlso hyper.NavigateUrl <> "") Then
        Return firstName.ToLower + "_" + lastName.ToLower + "_" + text
    Else
        Return Nothing
    End If
End Function

Return Nothing is not going to update the table field which is FileName. I want it to be NULL value. So I have used Return DBNull.Value.ToString(). But this doesn't add null instead blank field.

Is there any approach that I am missing?

Upvotes: 1

Views: 39

Answers (1)

Mary
Mary

Reputation: 15091

You can return "" of String.Empty in the Else section of your Function. The in the calling code check for String.IsNullOrEmpty and set the value of the parameter as shown.

Private Sub OPCode()
    Dim fileUp As New FileUpload
    Dim h As New Hyperlink
    Dim ReturnedString As String = checkFileNamesForUpdate(fileUp, "John", "Smith", "Some text", h)
    Using cn As New SqlConnection("Your connection string"),
            cmd As New SqlCommand("Update SomeTable Set FileName = @FileName;")
        cmd.Parameters.Add("@FileName", SqlDbType.VarChar, 100)
        If String.IsNullOrEmpty(ReturnedString) Then
            cmd.Parameters("@FileName").Value = DBNull.Value
        Else
            cmd.Parameters("@FileName").Value = ReturnedString
        End If
        cn.Open()
        cmd.ExecuteNonQuery()
    End Using
End Sub

Upvotes: 3

Related Questions