0

datagridview 列に英数字の入力のみを許可しようとしています。英数字の入力を許可し、ユーザーが負の数を入力したり、セルを空白のままにしたりできないようにする方法はありますか? 誰かが提案や答えを持っていれば、私はそれを大いに感謝します! :) 以下は私のコードです。すでに負のセルと空白のセルの検証が機能していますが、数値以外の入力を許可していません。

 If (e.ColumnIndex = 0) Then 'checking value for column 1 only
        Dim cellData = DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value
        If cellData Is Nothing OrElse IsDBNull(cellData) OrElse cellData.ToString = String.Empty Then ' This will prevent any blank cells
            MessageBox.Show("Name Cannot Be Empty")
            DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value = "Object" ' This is a default value that I want to supply after the message box
        ElseIf cellData < 0 Then
            MessageBox.Show("Negative Numbers Not Allowed") 'This prevents negative numbers
            DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value = "Object"
            Exit Sub ' Again this a default value I want supplied back to the datagridivewcell 



        End If
    End If

したがって、コードは機能しますが、数値以外の文字を入力すると、プログラムが停止して終了します。

4

1 に答える 1

1

次のように使用してみてくださいTryParse:

    If (e.ColumnIndex = 0) Then 'checking value for column 1 only
        Dim cellValue As Integer
        If (Int32.TryParse(DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value, cellValue)) Then
            If cellValue < 0 Then
                MessageBox.Show("Negative Numbers Not Allowed") 'This prevents negative numbers
                DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value = "Object"
                Exit Sub ' Again this a default value I want supplied back to the datagridivewcell 
            End If
        Else
            Dim testValue As String = DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value
            If (String.IsNullOrEmpty(testValue)) Then
                MessageBox.Show("Name Cannot Be Empty")
            DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value = "Object" ' This is a default value that I want to supply after the message box
            End If
        End If

    End If
于 2013-07-01T18:07:27.603 に答える