none
Entry of data in a DATAGRIDVIEW RRS feed

  • Question

  • I have a datagridview that contains 5 columns. The user is allowed to enter data in the second and third column. If the data entered in the second column is incorrect, I am display a message box with an error message and am able to change the background color for the cell to indicate an error. I am not able to get the cursor positioned in the cell containing the bad data.

    The following code executes in the CellValidated event for the grid.

         dgvBscvrgGrpCd.Rows(intCurrCellRow).Cells(intCurrCellCol).Style.BackColor = Color.Red
         MsgBox("Selected class number is not a valid class", vbExclamation, "CLASS ENTRY ERROR")
         dgvBscvrgGrpCd.ClearSelection()
         dgvBscvrgGrpCd.CurrentCell = dgvBscvrgGrpCd.Rows(intCurrCellRow).Cells(intCurrCellCol)
         dgvBcvrgGrpCd.Select()

    Any assistance is greatly appreciated.

    Tuesday, August 15, 2017 6:43 PM

Answers

  • Hello,

    The following code sample disallows exiting a cell deemed invalid be it text or numeric. The code below is from the code sample which loads some data from an xml file into the DataGridView. The first column in a real app would be a DataGridViewComboBox but that would not show how to demo what you are after.

    If the user wants to bail on an invalid entry they can press ESC key, otherwise enter valid data.

    Public Class Form1
        Private departmentNames As New List(Of String) From
            {
                "Psychology", "Chemistry", "Math", "Computer Science",
                "English", "French", "History", "Industrial Design", "Music"
            }
        Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    
            Dim Departments = From Items In XDocument.Load("Departments.xml")...<Departments>
                              Select
                              Department = Items.<DepartmentName>.Value,
                              Number = Items.<DepartmentNumber>.Value,
                              Rating = CDec(Items.<Rating>.Value)
    
            For Each Dept In Departments
                DataGridView1.Rows.Add(New Object() {Dept.Department, Dept.Number, Dept.Rating})
            Next
        End Sub
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            Dim CellDataList As String =
                String.Join(Environment.NewLine,
                            (
                                From T In DataGridView1.Rows.Cast(Of DataGridViewRow)()
                                Select CStr(T.Cells("DepartmentNumberColumn").Value)).ToArray
                            )
    
            MessageBox.Show(CellDataList)
        End Sub
    
        Private Sub DataGridView1_CellFormatting(sender As Object, e As DataGridViewCellFormattingEventArgs) Handles DataGridView1.CellFormatting
    
            If Not DataGridView1.Rows(e.RowIndex).IsNewRow Then
                If DataGridView1.Columns(e.ColumnIndex).Name.Equals("RatingColumn") Then
                    If e.Value Is Nothing Then
                        Exit Sub
                    End If
                    If Not e.Value.ToString.Contains(",") AndAlso Not e.Value.ToString.Contains(".") Then
                        e.Value = e.Value.ToString & ",00"
                    End If
                    If e.Value.ToString.Contains(".") Then
                        e.Value = e.Value.ToString.Replace(".", ",")
                    End If
                End If
            End If
        End Sub
    
        Sub DataGridView1_CellValidating(ByVal sender As Object, ByVal e As DataGridViewCellValidatingEventArgs) Handles DataGridView1.CellValidating
    
            Dim cell As DataGridViewCell = DataGridView1.Item(e.ColumnIndex, e.RowIndex)
    
            If cell.IsInEditMode Then
                Dim c As Control = DataGridView1.EditingControl
    
                If DataGridView1.Columns(e.ColumnIndex).Name = "DepartmentNumberColumn" Then
                    Dim IntValue As Integer = 0
                    If Not Integer.TryParse(c.Text, IntValue) Then
                        MessageBox.Show("Not valid")
                        e.Cancel = True
                    End If
                End If
    
                If DataGridView1.Columns(e.ColumnIndex).Name = "RatingColumn" Then
                    Dim DecValue As Decimal = 0
                    If Not Decimal.TryParse(c.Text, DecValue) Then
                        MessageBox.Show("Not valid")
                        e.Cancel = True
                    End If
                End If
    
                If DataGridView1.Columns(e.ColumnIndex).Name = "DepartmentNameColumn" Then
                    If String.IsNullOrEmpty(c.Text) Then
                        MessageBox.Show("Can not be empty")
                        e.Cancel = True
                    End If
                    If Not departmentNames.Contains(c.Text) Then
                        MessageBox.Show("Invalid department name")
                        e.Cancel = True
                    End If
                End If
            End If
    
        End Sub
    End Class
    


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Wednesday, August 16, 2017 9:54 AM
    Moderator

All replies

  • I have a datagridview that contains 5 columns. The user is allowed to enter data in the second and third column. If the data entered in the second column is incorrect, I am display a message box with an error message and am able to change the background color for the cell to indicate an error. I am not able to get the cursor positioned in the cell containing the bad data.

    The following code executes in the CellValidated event for the grid.

         dgvBscvrgGrpCd.Rows(intCurrCellRow).Cells(intCurrCellCol).Style.BackColor = Color.Red
         MsgBox("Selected class number is not a valid class", vbExclamation, "CLASS ENTRY ERROR")
         dgvBscvrgGrpCd.ClearSelection()
         dgvBscvrgGrpCd.CurrentCell = dgvBscvrgGrpCd.Rows(intCurrCellRow).Cells(intCurrCellCol)
         dgvBcvrgGrpCd.Select()

    Any assistance is greatly appreciated.

    Hi

    Here is some code that may help. Notice that I amusing the CelValidating event rather than the CellValidated event.

    This is a very trivial example, and just checks for particular strings as valid entries -where you would need a more comprehensive data validation instead. Also note: the starting data is NOT valid for the columns being checked and will error on cell leaving any of them unless changed to valid ("1234" or "2345") in this example.

    ' Form1 with blank DataGridView1
    Option Strict On
    Option Explicit On
    Public Class Form1
    
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            With DataGridView1
                .Columns.Add("Column1", "Decimal")
                .Columns.Add("Column2", "Integer")
                .Columns.Add("Column3", "Anything")
    
                ' add some example data
                .Rows.Add(1.234, 23, "Anything")
                .Rows.Add(11, 33, 66)
                .Rows.Add(21.234, 43, 77.77)
            End With
        End Sub
        Private Sub DataGridView1_CellValidating(sender As Object, e As DataGridViewCellValidatingEventArgs) Handles DataGridView1.CellValidating
            Dim obj As Object = e.FormattedValue
            If Not e.RowIndex = DataGridView1.NewRowIndex Then
                Select Case e.ColumnIndex
                    Case 1
                        ' check valid input here
                        If Not obj.ToString = "1234" Then
                            MessageBox.Show("Selected class number is not a valid class", "CLASS ENTRY ERROR", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                            DataGridView1.EndEdit()
                            DataGridView1(e.ColumnIndex, e.RowIndex).Value = Nothing
                            DataGridView1(e.ColumnIndex, e.RowIndex).Style.BackColor = Color.Red
                            e.Cancel = True
                        Else
                            DataGridView1(e.ColumnIndex, e.RowIndex).Style.BackColor = Color.FromKnownColor(KnownColor.ControlLightLight)
                        End If
                    Case 2
                        ' check valid input here
                        If Not obj.ToString = "2345" Then
                            MessageBox.Show("Column 2 Data Input Error", "CLASS ENTRY ERROR", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                            DataGridView1.EndEdit()
                            DataGridView1(e.ColumnIndex, e.RowIndex).Value = Nothing
                            DataGridView1(e.ColumnIndex, e.RowIndex).Style.BackColor = Color.DarkGreen
                            e.Cancel = True
                        Else
                            DataGridView1(e.ColumnIndex, e.RowIndex).Style.BackColor = Color.FromKnownColor(KnownColor.ControlLightLight)
                        End If
                End Select
            End If
        End Sub
    End Class


    Regards Les, Livingston, Scotland


    Tuesday, August 15, 2017 8:00 PM
  • Hello,

    The following code sample disallows exiting a cell deemed invalid be it text or numeric. The code below is from the code sample which loads some data from an xml file into the DataGridView. The first column in a real app would be a DataGridViewComboBox but that would not show how to demo what you are after.

    If the user wants to bail on an invalid entry they can press ESC key, otherwise enter valid data.

    Public Class Form1
        Private departmentNames As New List(Of String) From
            {
                "Psychology", "Chemistry", "Math", "Computer Science",
                "English", "French", "History", "Industrial Design", "Music"
            }
        Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    
            Dim Departments = From Items In XDocument.Load("Departments.xml")...<Departments>
                              Select
                              Department = Items.<DepartmentName>.Value,
                              Number = Items.<DepartmentNumber>.Value,
                              Rating = CDec(Items.<Rating>.Value)
    
            For Each Dept In Departments
                DataGridView1.Rows.Add(New Object() {Dept.Department, Dept.Number, Dept.Rating})
            Next
        End Sub
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            Dim CellDataList As String =
                String.Join(Environment.NewLine,
                            (
                                From T In DataGridView1.Rows.Cast(Of DataGridViewRow)()
                                Select CStr(T.Cells("DepartmentNumberColumn").Value)).ToArray
                            )
    
            MessageBox.Show(CellDataList)
        End Sub
    
        Private Sub DataGridView1_CellFormatting(sender As Object, e As DataGridViewCellFormattingEventArgs) Handles DataGridView1.CellFormatting
    
            If Not DataGridView1.Rows(e.RowIndex).IsNewRow Then
                If DataGridView1.Columns(e.ColumnIndex).Name.Equals("RatingColumn") Then
                    If e.Value Is Nothing Then
                        Exit Sub
                    End If
                    If Not e.Value.ToString.Contains(",") AndAlso Not e.Value.ToString.Contains(".") Then
                        e.Value = e.Value.ToString & ",00"
                    End If
                    If e.Value.ToString.Contains(".") Then
                        e.Value = e.Value.ToString.Replace(".", ",")
                    End If
                End If
            End If
        End Sub
    
        Sub DataGridView1_CellValidating(ByVal sender As Object, ByVal e As DataGridViewCellValidatingEventArgs) Handles DataGridView1.CellValidating
    
            Dim cell As DataGridViewCell = DataGridView1.Item(e.ColumnIndex, e.RowIndex)
    
            If cell.IsInEditMode Then
                Dim c As Control = DataGridView1.EditingControl
    
                If DataGridView1.Columns(e.ColumnIndex).Name = "DepartmentNumberColumn" Then
                    Dim IntValue As Integer = 0
                    If Not Integer.TryParse(c.Text, IntValue) Then
                        MessageBox.Show("Not valid")
                        e.Cancel = True
                    End If
                End If
    
                If DataGridView1.Columns(e.ColumnIndex).Name = "RatingColumn" Then
                    Dim DecValue As Decimal = 0
                    If Not Decimal.TryParse(c.Text, DecValue) Then
                        MessageBox.Show("Not valid")
                        e.Cancel = True
                    End If
                End If
    
                If DataGridView1.Columns(e.ColumnIndex).Name = "DepartmentNameColumn" Then
                    If String.IsNullOrEmpty(c.Text) Then
                        MessageBox.Show("Can not be empty")
                        e.Cancel = True
                    End If
                    If Not departmentNames.Contains(c.Text) Then
                        MessageBox.Show("Invalid department name")
                        e.Cancel = True
                    End If
                End If
            End If
    
        End Sub
    End Class
    


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Wednesday, August 16, 2017 9:54 AM
    Moderator
  • Thank you for giving solution.
    Wednesday, August 16, 2017 10:34 AM
  • Hi Stephen Spohn,

    Do resolve the your issue, if yes, could you please mark helpful reply as answer or share your solution, it will be beneficial to other communities who have the similar issue.

    If not, please provide a bit more information and feel free let us know.

    Best regards,

    Cole


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Friday, August 25, 2017 7:05 AM
    Moderator