Reputation: 1
I wrote a simple code for validation with VB.NET. This code is storing EMPTY data in the database table. How do I avoid this, and what code do I write after the else if
statements? i.e after the Phone no validation.
This is the code below:
Protected Sub Button1_Click(sender As Object, e As System.EventArgs) Handles Button1.Click
If Len(Trim(txtName.Text)) = 0 Then
MsgBox("Enter Name", MsgBoxStyle.Critical, "Error")
txtName.Focus()
ElseIf Len(Trim(txtAge.Text)) = 0 Then
MsgBox("Enter Age", MsgBoxStyle.Critical, "Error")
txtAge.Focus()
ElseIf Len(Trim(txtPhone.Text)) = 0 Then
MsgBox("Enter Phone", MsgBoxStyle.Critical, "Error")
txtPhone.Focus()
Else
Dim blnFlag As Boolean = False
MsgBox("Enter the details", MsgBoxStyle.Critical, "Error")
End If
Try
Dim strCommand As String
strCommand = "Insert into [Validation] ([Name],[Age],[Phone]) VALUES"
strCommand = strCommand & "('" & Trim(txtName.Text) & "','" & Trim(txtAge.Text) & "','" & Trim(txtPhone.Text) & "')"
Dim StrConnection As String
StrConnection = ConfigurationManager.ConnectionStrings("ConnectionString").ToString
Dim cnValidation As New SqlClient.SqlConnection(StrConnection)
If (cnValidation.State = ConnectionState.Closed) Then
cnValidation.Open()
End If
Dim cmdEmployee As New SqlClient.SqlCommand(strCommand, cnValidation)
cmdEmployee.ExecuteNonQuery()
cnValidation.Close()
MsgBox("Save Successful", MsgBoxStyle.Information, "Success")
Catch ex As Exception
MsgBox("Save failed " & ex.Message, MsgBoxStyle.Critical, "Failed")
End Try
Upvotes: 0
Views: 238
Reputation: 460380
The easiest approach is, return from the method after your validation failed:
If Len(Trim(txtName.Text)) = 0 Then
MsgBox("Enter Name", MsgBoxStyle.Critical, "Error")
txtName.Focus()
Return
ElseIf Len(Trim(txtAge.Text)) = 0 Then
MsgBox("Enter Age", MsgBoxStyle.Critical, "Error")
txtAge.Focus()
Return
ElseIf Len(Trim(txtPhone.Text)) = 0 Then
MsgBox("Enter Phone", MsgBoxStyle.Critical, "Error")
txtPhone.Focus()
Return
Else
Dim blnFlag As Boolean = False
MsgBox("Enter the details", MsgBoxStyle.Critical, "Error")
Return
End If
However, the "Enter the details"
part is not clear. Why do you show the error-MessageBox always? There seems to be a logical problem. I'll ignore this part henceforth.
Here's a more readable .NET version of your code:
Dim validName = Not String.IsNullOrWhiteSpace(txtName.Text)
Dim validAge = Not String.IsNullOrWhiteSpace(txtAge.Text)
Dim validPhone = Not String.IsNullOrWhiteSpace(txtPhone.Text)
Dim isValid = validName AndAlso validAge AndAlso validPhone
If Not isValid Then
If Not validName Then
MsgBox("Enter Name", MsgBoxStyle.Critical, "Error")
txtName.Focus()
ElseIf Not validAge Then
MsgBox("Enter Age", MsgBoxStyle.Critical, "Error")
txtAge.Focus()
ElseIf Not validPhone Then
MsgBox("Enter Phone", MsgBoxStyle.Critical, "Error")
txtPhone.Focus()
End If
Return ' return from this method '
Else
' insert into DB '
' .... '
End If
Side-note: you should really use sql-parameters even if this a windows-application. It will not only prevent you from sql-injection attacks but can also prevent localization issues (f.e. with datetime
):
Try
Dim newIdenity As Int32 ' determine new ID generated from database '
Dim strCommand = "Insert into [Validation] ([Name],[Age],[Phone]) VALUES (@Name,@Age,@Phone)"
Dim StrConnection As String = ConfigurationManager.ConnectionStrings("ConnectionString").ToString
Using cnValidation = New SqlClient.SqlConnection(StrConnection)
Using cmdEmployee = New SqlCommand(strCommand, cnValidation)
cnValidation.Open()
cmdEmployee.Parameters.AddWithValue("@Name",txtName.Text)
cmdEmployee.Parameters.AddWithValue("@Age",Int32.Parse(txtAge.Text))
cmdEmployee.Parameters.AddWithValue("@Phone",txtPhone.Text)
newIdenity = DirectCast(cmdEmployee.ExecuteScalar(), Int32)
End Using
End Using
MsgBox("Save Successful", MsgBoxStyle.Information, "Success")
Catch ex As Exception
MsgBox("Save failed " & ex.Message, MsgBoxStyle.Critical, "Failed")
End Try
You should use the Using
-statement for everything implementiong IDisposable
which disposes unmanaged resources, it'll also close the connection, even on error.
I've also shown how you can determine the newly created identity value from an IDENTITY
column in sql-server.
Note that i have parsed txtAge.Text
to Int32
since i assume that the type of the columns in the database is actually int
. If this is not the case remove the Int32.Parse
. In general you should always provide the correct type as parameter.
Upvotes: 2