2
votes

I have a vb.net windows form application using a datagridview. I'm hoping to find a way to prevent a user from entering whitespaces or empty strings and if they enter invalid input. I'll have a message appear explaining their mistake and thereafter a default value will be supplied. This is what I have so far and it prevents completely blank cells but if I had a whitespace (i.e. press space bar to add blank string) it doesn't know that it's still blank input.

If (columnindex = 0) Then 'checking value for column 1 only
        Dim cellString = DataGridView1.Rows(rowindex).Cells(columnindex).value
        If cellString Is Nothing OrElse IsDBNull(cellString) OrElse cellString.ToString = String.Empty Then

            MessageBox.Show("Cannot Be Empty")
            DataGridView1.Rows(rowindex).Cells(columnindex).value = "Default Value"
            Exit Sub
        End If
3

3 Answers

3
votes

Use String.IsNullOrWhiteSpace method From MSDN
Then datagridview.Rows(0).Cells(0).Value.ToString() return empty string if value is DBNull, so you don't need to check for this too

If (columnindex = 0) Then 'checking value for column 1 only
    Dim cellString as String = DataGridView1.Rows(rowindex).Cells(columnindex).value.ToString()
    If String.IsNullOrWhiteSpace(cellString) = True Then

        MessageBox.Show("Cannot Be Empty")
        DataGridView1.Rows(rowindex).Cells(columnindex).value = "Default Value"
        Exit Sub
    End If
End If
0
votes

Loop for each character in your string, if you find a valid character then your string is valid

Something like this:

 Dim IsValid as Boolean=false 

For I = 0 to cellstring.length - 2

    if Cellstring.substring(I,1) <> " " then IsValid = true

Next
0
votes

You can use the EditingControlShowing event to register a KeyPress function for the input box.

Private Sub YourDataGridView_EditingControlShowing(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles YourDataGridView.EditingControlShowing

    Try
        RemoveHandler e.Control.KeyPress, AddressOf YourFunctionToPreventWhiteSpace
    Catch ex As Exception
    End Try

    AddHandler e.Control.KeyPress, AddressOf YourFunctionToPreventWhiteSpace

End Sub

Private Sub YourFunctionToPreventWhiteSpace(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs)

    If Char.IsWhiteSpace(e.KeyChar) Then
        MsgBox("Your message.", MsgBoxStyle.Exclamation)
        e.Handled = True
    End If

End Sub