4

I am new to winforms..I am trying to set two column of DataGridView to Numeric Only.. I do not want user to be able to type anything into a cell unless its a natural number in one column and a numeric value in another(which always one decimal). I thought this would be simple.. but even after trying a lot of things from stackoverflow and other sites i am still unable to achieve this.

If DataGridView1.CurrentCell.ColumnIndex = 8 Then

    If Not Char.IsControl(e.KeyChar) AndAlso Not Char.IsDigit(e.KeyChar) AndAlso e.KeyChar <> "."c Then
        e.Handled = True
    End If

End If 
Md. Suman Kabir
  • 5,243
  • 5
  • 25
  • 43
SamuraiJack
  • 5,131
  • 15
  • 89
  • 195
  • I will accept any answer in c# too if it works.. There are online converters available. ;) – SamuraiJack Nov 08 '13 at 09:57
  • Duplicate Question [Make a specific column only accept numeric value in datagridview in Keypress event][1] [1]: http://stackoverflow.com/questions/12645458/make-a-specific-column-only-accept-numeric-value-in-datagridview-in-keypress-eve – chipsnchops Nov 08 '13 at 10:06
  • used **EditingControlShowing** instead of CellValidating see [link](https://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.editingcontrolshowing(v=vs.110).aspx) – Ramgy Borja Aug 03 '17 at 03:10

9 Answers9

13

Try this code

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

        If DataGridView1.CurrentCell.ColumnIndex = 2 Then

            AddHandler CType(e.Control, TextBox).KeyPress, AddressOf TextBox_keyPress

        ElseIf DataGridView1.CurrentCell.ColumnIndex = 1 Then

            AddHandler CType(e.Control, TextBox).KeyPress, AddressOf TextBox_keyPress1


        End If

    End Sub

    Private Sub TextBox_keyPress(ByVal sender As Object, ByVal e As KeyPressEventArgs)

        If Char.IsDigit(CChar(CStr(e.KeyChar))) = False Then e.Handled = True

    End Sub

    Private Sub TextBox_keyPress1(ByVal sender As Object, ByVal e As KeyPressEventArgs)

        If Not (Char.IsDigit(CChar(CStr(e.KeyChar))) Or e.KeyChar = ".") Then e.Handled = True

    End Sub

TextBox_keyPress Event for only numeric

TextBox_keyPress1 Event for numeric with decimal value

Sathish
  • 4,419
  • 4
  • 30
  • 59
  • I am trying to validate `DataGridViewTextBoxCell` I am not using TextBox. – SamuraiJack Nov 09 '13 at 05:20
  • 1
    yes. you are not using texbox. but you can achieve your goal by writing textbox event and add handler in the DataGridView1_EditingControlShowing event.. you no need to add text box in the form design.. – Sathish Nov 09 '13 at 07:36
  • This my friend is by far the best solution I have come across so far.. I am sorry i took so long to respond. Thanks. However there is only one thing lacking, which is.. In case of decimal numbers only single decimal is to be allowed. – SamuraiJack Nov 11 '13 at 04:37
  • @Arbaaz format the decimal cell after the editing or check the particular cell have decimal value. I think format (#,0.0) is the best sloution – Sathish Nov 11 '13 at 07:23
  • well i tried to check if the cell already has decimal but i always get null reference error ... I have asked this in a new question .. http://stackoverflow.com/q/19899456/2064292 – SamuraiJack Nov 11 '13 at 07:35
1

If data type validation is only concern then you can use CellValidating event like this

    private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
    {
        //e.FormattedValue  will return current cell value and 
        //e.ColumnIndex & e.RowIndex will rerurn current cell position

        // If you want to validate particular cell data must be numeric then check e.FormattedValue is all numeric 
        // if not then just set  e.Cancel = true and show some message 
        //Like this 

        if (e.ColumnIndex == 1)
        {
            if (!IsNumeric(e.FormattedValue))  // IsNumeric will be your method where you will check for numebrs 
            {
                MessageBox.Show("Enter valid numeric data");
                dataGridView1.CurrentCell.Value = null;
                e.Cancel = true;

            }

        }

    }
Neeraj Kumar Gupta
  • 2,157
  • 7
  • 30
  • 58
0
If e.ColumnIndex = 6 Then
    If Not IsNumeric(e.FormattedValue) Then
        ' IsNumeric will be your method where you will check for numebrs 
        MessageBox.Show("Enter valid numeric data")
        DataGridView1.CurrentCell.Value = Nothing

        e.Cancel = True

    End If
End If
bytecode77
  • 14,163
  • 30
  • 110
  • 141
0

Following code is an extension of Satish's Solution. It will help to control values of DataGridView Cells. Textbox function has used to attach a cell to textbox-event only. No need to add a text box in a DataGridView or anywhere on the form.

Private Sub DataGridView_EditingControlShowing(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles DataGridView.EditingControlShowing
    If DataGridView.CurrentCell.ColumnIndex = 2 Then 'Numeric column with decimal point
        AddHandler CType(e.Control, TextBox).KeyPress, AddressOf TextBox_keyPress

    ElseIf DataGridView.CurrentCell.ColumnIndex = 3 Then 'Numeric column without Decimal
        AddHandler CType(e.Control, TextBox).KeyPress, AddressOf TextBox_keyPress1

    ElseIf DataGridView.CurrentCell.ColumnIndex = 4 Then 'Selected Values only
        AddHandler CType(e.Control, TextBox).KeyPress, AddressOf TextBox_keyPress2

    ElseIf DataGridView.CurrentCell.ColumnIndex = 5 Then 'Email Column
        AddHandler CType(e.Control, TextBox).KeyPress, AddressOf TextBox_keyPress3

    End If

End Sub

Private Sub TextBox_keyPress(ByVal sender As Object, ByVal e As KeyPressEventArgs)
    'Allows Numeric values, one decimal point and BackSpace key
    Dim numbers As Windows.Forms.TextBox = sender
    If InStr("1234567890.", e.KeyChar) = 0 And Asc(e.KeyChar) <> 8 Or (e.KeyChar = "." And InStr(numbers.Text, ".") > 0) Then
        e.KeyChar = Chr(0)
        e.Handled = True
    End If
End Sub

Private Sub TextBox_keyPress1(ByVal sender As Object, ByVal e As KeyPressEventArgs)
    'Allow Numeric values, BackSpace key. Disallows decimal point (i.e. dot) 
    Dim numbers As Windows.Forms.TextBox = sender
    If InStr("1234567890", e.KeyChar) = 0 And Asc(e.KeyChar) <> 8 Then
        e.KeyChar = Chr(0)
        e.Handled = True
    End If
End Sub


Private Sub TextBox_keyPress2(ByVal sender As Object, ByVal e As KeyPressEventArgs)
    'Allow selected values only
    If InStr("1234567890!@#$%^&*()_+=-", e.KeyChar) > 0 Then
        e.KeyChar = Chr(0)
        e.Handled = True
    End If
End Sub

Private Sub TextBox_keyPress3(ByVal sender As Object, ByVal e As KeyPressEventArgs)
    'Martch function, Needs to add "Imports System.Text.RegularExpressions" at the top of Class
    'Allows Email values
    Dim Email As Windows.Forms.TextBox = sender
    If Email.Text <> "" Then
        Dim rex As Match = Regex.Match(Trim(Email.Text), "^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,3})$", RegexOptions.IgnoreCase)
        If rex.Success = False Then
            MessageBox.Show("Please Enter a valid Email Address", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information)
            Email.BackColor = Color.Red
            Email.Focus()
            Exit Sub
        Else
            Email.BackColor = Color.White
        End If
    End If
End Sub
0

Try this code. Its almost the same as the most votes answer, but I edited KeypressEvent codes to make it simple and you can use this even you have to enter decimal numbers. Enjoy. :)

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

    If DataGridView1.CurrentCell.ColumnIndex = 2 Then

        AddHandler CType(e.Control, TextBox).KeyPress, AddressOf TextBox_keyPress

    End If

End Sub

Private Sub TextBox_keyPress(ByVal sender As Object, ByVal e As KeyPressEventArgs)

     If (Not Char.IsControl(e.KeyChar) _
                AndAlso (Not Char.IsDigit(e.KeyChar) _
                AndAlso (e.KeyChar <> Microsoft.VisualBasic.ChrW(46)))) Then
        e.Handled = True
    End If

End Sub
Murmel
  • 5,402
  • 47
  • 53
Peterboy
  • 1
  • 1
0
Private Sub DGV_EditingControlShowing(sender As Object, e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles DGV_TimeSheetMain.EditingControlShowing
    '       '*************Allow only Numbers in DataGridView*************
    Dim txtEdit As TextBox = e.Control
    'remove any existing handler
    RemoveHandler txtEdit.KeyPress, AddressOf TextEdit_Keypress
    AddHandler txtEdit.KeyPress, AddressOf TextEdit_Keypress
End Sub

Private Sub TextEdit_Keypress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs)
    'Test for numeric value or backspace in first column
    If DGV.CurrentCell.ColumnIndex = 1 Then
        If IsNumeric(e.KeyChar.ToString()) Or e.KeyChar = ChrW(Keys.Back) Then
            e.Handled = False 'if numeric display
        Else
            e.Handled = True  'if non numeric don't display
        End If
    End If
End Sub
0

Try This with lambda

Private Sub dgv_pararelhp_EditingControlShowing(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles dgv_pararelhp.EditingControlShowing
    If dgv_pararelhp.CurrentCell.ColumnIndex = 0 Then'// change this optional your index column.
         AddHandler CType(e.Control, TextBox).KeyPress, Sub(s_, e_)
                                                            If Char.IsDigit(CChar(CStr(e_.KeyChar))) = False Then e_.Handled = True
                                                         End Sub
       End If
End Sub
Fajarsoft
  • 41
  • 4
0

I tried Sathish answer but i can't use the backspace so i tried this instead for the keypress event

Private Sub TextBox_keyPress(ByVal sender As Object, ByVal e As KeyPressEventArgs)

    If (Not Char.IsControl(e.KeyChar) _
   AndAlso (Not Char.IsDigit(e.KeyChar) _
   AndAlso (e.KeyChar <> Microsoft.VisualBasic.ChrW(46)))) Then
        e.Handled = True
    End If
End Sub
Karl
  • 36
  • 7
-1
Private Sub DataGridView1_EditingControlShowing(ByVal sender As Object, ByVal e As         System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles DataGridView1.EditingControlShowing
        AddHandler CType(e.Control, TextBox).KeyPress, AddressOf TextBox_keyPress
 End Sub
 Private Sub TextBox_keyPress(ByVal sender As Object, ByVal e As KeyPressEventArgs)
        If Char.IsDigit(CChar(CStr(e.KeyChar))) = False Then e.Handled = True
        If Not (Char.IsDigit(CChar(CStr(e.KeyChar))) Or e.KeyChar = ".") Then e.Handled = True
        If e.KeyChar = " "c Then e.Handled = False
  End Sub
d4Rk
  • 6,622
  • 5
  • 46
  • 60