Reputation: 138
I am creating a windows form that the user will fill out whenever we add a new employee. If I fill in the form completely, I can write to the database, but if one field gets left blank, I get an error. In the SQL table, all rows are set to allow nulls, and I can insert via SQL Server Management Studio with null values with no problems.
For brevity, I have left off a dozen or so fields, but the same error occurs if I replace this code with the code I am using.
Dim DBConnection As New SqlClient.SqlConnection
Dim cmd As New SqlClient.SqlCommand
Try
WOWConnection.ConnectionString = "Server=MyServerName;Database=Employee Database;Trusted_Connection=TRUE;"
WOWConnection.Open()
cmd.Connection = WOWConnection
cmd.CommandText = "INSERT INTO [dbo].[Employees]([FirstName],[LastName]) VALUES (@FirstName,@LastName)"
cmd.Parameters.AddWithValue("@FirstName", Me.EMP_FirstName.Text)
cmd.Parameters.AddWithValue("@LastName", Me.EMP_LastName.Text)
cmd.ExecuteNonQuery()
MsgBox("Sucess!")
Catch ex As Exception
MsgBox("error")
Finally
DBConnection.Close()
End Try
How do you handle a field being left blank on a windows form?
Upvotes: 1
Views: 422
Reputation: 7689
Test the value being inserted before passing the value to SQL. Note that NULL value and Empty is not the same in SQL.
cmd.CommandText = "INSERT INTO [dbo].Employees VALUES (@FirstName,@LastName)"
If Not string.IsNullOrEmpty(Me.EMP_FirstName.Text) Then
cmd.Parameters.AddWithValue("@FirstName", Me.EMP_FirstName.Text)
Else
cmd.Parameters.AddWithValue("@FirstName", DBNull.Value)
EndIf
cmd.ExecuteNonQuery()
Upvotes: 1