【问题标题】:How to prevent white space in datagridview vb.net如何防止datagridview vb.net中的空白
【发布时间】:2014-01-15 15:02:49
【问题描述】:

我有一个使用 datagridview 的 vb.net windows 窗体应用程序。我希望找到一种方法来防止用户输入空格或空字符串以及如果他们输入无效输入。我会出现一条消息来解释他们的错误,然后会提供一个默认值。这是我到目前为止所拥有的,它可以防止完全空白的单元格,但如果我有一个空格(即按空格键添加空白字符串)它不知道它仍然是空白输入。

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

【问题讨论】:

    标签: vb.net winforms validation datagridview


    【解决方案1】:

    使用String.IsNullOrWhiteSpace方法From MSDN
    然后datagridview.Rows(0).Cells(0).Value.ToString()如果值为DBNull则返回空字符串,所以你也不需要检查这个

    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
    

    【讨论】:

      【解决方案2】:

      循环遍历字符串中的每个字符,如果找到有效字符,则字符串有效

      类似这样的:

       Dim IsValid as Boolean=false 
      
      For I = 0 to cellstring.length - 2
      
          if Cellstring.substring(I,1) <> " " then IsValid = true
      
      Next
      

      【讨论】:

      • 感谢您的帮助。但是循环不适用于我的特殊情况,我的 datagridview 有数千行,循环会减慢它的速度。
      • 也许这比 String.IsNullOrWhiteSpace 快,当然这肯定也会为您的字符串创建一个循环,您不编写循环这一事实并不意味着它没有这样做。如果性能对您的应用程序真的很重要,您必须测试哪种方式更快。那条线很好,我不知道它存在
      【解决方案3】:

      您可以使用EditingControlShowing事件为输入框注册KeyPress函数。

      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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-06-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-05-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多