Q: How to do DataGridView cell validation?
A: If you want take input directly in datagridview, column of string type takes any input but DataGridView default error dialog is shown when making invalid input i-e 123a for integer type column that asks to handle the DataError event of datagridview .
So you can use CellValidating event of DataGridView to validate integer type column as well as other.
Steps:
- Use DataGridView's CellValidating event
- Get the cell for which the event is called
- If the cell is in EditMode then
- Perform validation
CellValidating Event:
Dim cell As DataGridViewCell = DataGridView1.Item(e.ColumnIndex, e.RowIndex)
If cell.IsInEditMode Then
Dim c As Control = DataGridView1.EditingControl
Select Case DataGridView1.Columns(e.ColumnIndex).Name
Case "sessno", "rno" c.Text = CleanInputNumber(c.Text)
Case "name" c.Text = CleanInputAlphabet(c.Text)
End Select
End If
End Sub
If cell.IsInEditMode Then
Dim c As Control = DataGridView1.EditingControl
Select Case DataGridView1.Columns(e.ColumnIndex).Name
Case "sessno", "rno" c.Text = CleanInputNumber(c.Text)
Case "name" c.Text = CleanInputAlphabet(c.Text)
End Select
End If
End Sub
Utility Functions:
Code:
Private Function CleanInputAlphabet(ByVal str As String) As String Return System.Text.RegularExpressions.Regex.Replace(str, "[0-9\b\s-]", "")
End Function
Code:
Private Function CleanInputNumber(ByVal str As String) As String Return System.Text.RegularExpressions.Regex.Replace(str, "[a-zA-Z\b\s-.]", "")
End Function
Tidak ada komentar:
Posting Komentar