Link to home
Create AccountLog in
Avatar of Victor  Charles
Victor CharlesFlag for United States of America

asked on

Help with formating Cell in DataGridView


How do you force users to enter only 15 characters in a particular  column of a DatagridView  using VB.NET?


Avatar of Rgonzo1971


Maybe like this

CType(Me.DataGridView1.Columns(0), DataGridViewTextBoxColumn).MaxInputLength = 10  

Open in new window

Avatar of Victor  Charles


Thanks, how do you force users to enter data in the following  format. 99,999,99? Where 9 are numeric values only.

dataGridView1.Columns(0).DefaultCellStyle.Format = "00,000,00"
' and
Private Sub DataGridView1_KeyPress(sender As Object, e As     System.Windows.Forms.KeyPressEventArgs) Handles DataGridView1.KeyPress
    If (Char.IsDigit(e.KeyChar)) Then
        'this is a number
        e.Handled = True
        'not a number
    End If
End Sub

Open in new window

Thank you for the links.
Here is a solution that lets you do two things:
    - Validate each character on KeyPress and suppress those that are invalid
    - Check the current cell value *PRIOR* to this character for content and/or format

My example below restricts the cell to numeric only with no more than one decimal point but you can change the validation to fit your needs.

e.Handled = True will BLOCK the character
e.Handled = False (the default state so it's implicite) will ALLOW the character

These Events fire BEFORE the character is added to the cell value.......

--- %< --- Cut Here --- %< --- Cut Here --- %< --- Cut Here --- %< --- Cut Here ---

    Private Sub dgv_EditingControlShowing(sender As Object, e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles dgv.EditingControlShowing
        Dim txtEdit As TextBox = e.Control
        'remove any existing handler
        RemoveHandler txtEdit.KeyPress, AddressOf dgv_KeyPress
        AddHandler txtEdit.KeyPress, AddressOf dgv_KeyPress
    End Sub

    Private Sub dgv_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs)
        If Not String.Format("0123456789.{0}{1}", ChrW(Keys.Back), ChrW(Keys.Delete)).Contains(e.KeyChar) Then
            'Suppress non-numeric characters
            e.Handled = True
            If (e.KeyChar = ".") And (DirectCast(sender, TextBox).Text.IndexOf(".") > -1) Then
                'Only one decimal point per customer please
                e.Handled = True
            End If
        End If
    End Sub

--- %< --- Cut Here --- %< --- Cut Here --- %< --- Cut Here --- %< --- Cut Here ---
Avatar of Swamp_Thing
Flag of United States of America image

Link to home
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
Thank you.