2011-11-10 84 views
0

我能夠驗證單元格是否爲空,但我無法檢查單元格的長度。我希望用戶輸入5位數字,如果它小於5,則顯示一個消息框。如何檢查datagrid視圖中單元格的長度值?

我試過cellvalue.length方法,但它不工作。

Private Sub dgvResults_CellValidating(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellValidatingEventArgs) Handles dgvResults.CellValidating 
     'variables 
     Dim columnName As String = dgvResults.Columns(e.ColumnIndex).Name 
     Dim cellVal As String = e.FormattedValue.ToString() 

     'Datagrid view validation 
     If ((e.ColumnIndex = 0) And (e.FormattedValue = "") And (Not (cellVal.Length = 5))) Then 
      e.Cancel = True 
      MessageBox.Show(columnName & " must be 5 Digits Long!") 
     ElseIf (e.ColumnIndex = 1 And e.FormattedValue = "") Then 
      e.Cancel = True 
      MessageBox.Show(columnName & " cannot be blank!") 
     ElseIf (e.ColumnIndex = 2 And e.FormattedValue = "") Then 
      e.Cancel = True 
      MessageBox.Show(columnName & " cannot be blank!") 
     ElseIf ((e.ColumnIndex = 3) And (e.FormattedValue = "") And (Not IsNumeric(e.FormattedValue))) Then 
      e.Cancel = True 
      MessageBox.Show(columnName & " cannot be blank!") 
     ElseIf ((e.ColumnIndex = 4) And (Not IsNumeric(e.FormattedValue))) Then 
      e.Cancel = True 
      MessageBox.Show(columnName & " cannot be blank!") 
     End If 

    End Sub 

回答

1

以下原因你的代碼到不行:

(e.FormattedValue = "") And (Not (cellVal.Length = 5)) 

要檢查是否爲空值它的長度<> 5.

但是你想確保t帽子cellVal.Length = 5:

If e.ColumnIndex = 0 AndAlso cellVal.Length <> 5 Then 
     e.Cancel = True 
     MessageBox.Show(columnName & " must be 5 Digits Long!") 
End If 
+0

是的,它的工作。你是對的。謝謝你 – user804437

-1

我認爲你將需要:

cellval.text.length 
+0

-1:'cellval'是一個'String'本身。 –

+0

對不起,沒有正確閱讀。 早起,我的壞:( –

相關問題