Cell Validation in Datagridview?

rajesh.forum

Well-known member
Joined
Sep 7, 2007
Messages
55
Programming Experience
Beginner
hi all!!!!!!
I need to validate a particular cell in the way it shud accept only numbers.



regards rajesh
 
Perhaps like this with CellValidating event:
VB.NET:
Private Sub DataGridView1_CellValidating(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellValidatingEventArgs) Handles DataGridView1.CellValidating
    If Integer.TryParse(e.FormattedValue, Nothing) Then
        ErrorProvider1.SetError(sender, Nothing)
    Else
        e.Cancel = True
        ErrorProvider1.SetError(sender, "must be number")
    End If
End Sub
 
Thanks for ur post,but shud not allow the numerics

HI
Thanks for ur post.But this is not wat i want.I shud not allow the numerics while entering the data in a particular cell in datagridview .For example,in the 3rd column of the datagridview..







regards,
rajesh.
 
In that case you have to inherit and change the behaviour of the DataGridViewTextBoxCell. Here you can use the Initialize/Detach overrides for EditingControl and attach for example to the TextChanged event, using it to remove non-digits. Example:
VB.NET:
Class dgvTbNumericCell
    Inherits DataGridViewTextBoxCell

    Public Overrides Sub InitializeEditingControl(ByVal rowIndex As Integer, _
    ByVal initialFormattedValue As Object, _
    ByVal dataGridViewCellStyle As System.Windows.Forms.DataGridViewCellStyle)
        MyBase.InitializeEditingControl(rowIndex, initialFormattedValue, dataGridViewCellStyle)
        AddHandler Me.DataGridView.EditingControl.TextChanged, AddressOf tb_TextChanged
    End Sub

    Public Overrides Sub DetachEditingControl()
        MyBase.DetachEditingControl()
        RemoveHandler Me.DataGridView.EditingControl.TextChanged, AddressOf tb_TextChanged
    End Sub

    Private Sub tb_TextChanged(ByVal sender As Object, ByVal e As EventArgs)
        Dim tb As TextBox = sender ' or Me.DataGridView.EditingControl
        tb.Text = System.Text.RegularExpressions.Regex.Replace(tb.Text, "\D", "")
        tb.SelectionStart = tb.TextLength
    End Sub
End Class
then you use this cell as template for a new DataGridViewColumn:
VB.NET:
DataGridView1.Columns.Add(New DataGridViewColumn(New dgvTbNumericCell))
it can also be set as cell template for an existing DataGridViewTextBoxColumn, but will only affect cells created after this new template was assigned:
VB.NET:
DataGridView1.Columns(0).CellTemplate = New dgvTbNumericCell
 
Back
Top