none
How to change the value of a cell in DataGridView.CellValidating event ?

    Question

  • I handle the validation in the CellValidating event, and if the cell is invalid display an error message, then cancel the exit of edit mode. However I would also like to erase the content of the cell currently in edit mode. Anyone knows how ? Tx.

    Thursday, September 08, 2011 3:12 PM

Answers

  • Try it by changing like this in my sample

    Public Class Form1
        Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            Dim dt As New DataTable
            Dim dc1 As New DataColumn
            Dim dc2 As New DataColumn
            dt.Columns.Add(dc1)
            dt.Columns.Add(dc2)
            For i = 0 To 3
                dt.Rows.Add(dt.NewRow)
                dt.Rows(i)(1) = CStr(i)
            Next
            dt.Rows(0)(0) = "Liliane"
            dt.Rows(1)(0) = "John"
            dt.Rows(2)(0) = "Armin"
            dt.Rows(3)(0) = "Ken"
            DataGridView1.DataSource = dt
        End Sub
        Private Sub DataGridView1_CellValidating(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellValidatingEventArgs) Handles DataGridView1.CellValidating
            Dim DGV As DataGridView = CType(sender, DataGridView)
            Dim cell As DataGridViewTextBoxCell = CType(DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex), DataGridViewTextBoxCell)
            If cell.IsInEditMode Then
                If CStr(e.FormattedValue) = "Cor" Then
                    MessageBox.Show("Cell value is invalid", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
                    DataGridView1.CancelEdit()
                End If
            End If
        End Sub
    End Class
    



    Success
    Cor
    • Marked as answer by RebootUniverse Tuesday, September 13, 2011 1:56 PM
    Tuesday, September 13, 2011 1:40 PM
  • Yeah by calling e.Cancel you are effectively preventing the code from getting past the Validating event of the cell, which means you cant do anything until a valid input has been entered (you can press ESC to exiting edit mode of course).

    Do you really need to clear the contents of the entire cell?  Perhaps it may be better to inform the user that the cell must be a valid integer and have them correct the value e.g. using a messagebox as in the example.  It may be irritating if the user has entered a large integer in there (say a bank account number), and accidently added a letter at the end, only to find that they have to re-input the whole number all over again for a trivial mistake (esspecially if you're like me and cant remember your account numbers off the top of your head!).

    I think you may have to look outside the validating event to get the effect your after, but i was struggling trying to find an alternative that allows you to cancel the event and have the application re-enter edit mode of the invalid cell, as you want.

     

    • Marked as answer by RebootUniverse Tuesday, September 13, 2011 4:46 PM
    Tuesday, September 13, 2011 1:01 PM

All replies

  • Private Sub DataGridView1_CellValidating(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellValidatingEventArgs) Handles DataGridView1.CellValidating
    
            Dim cell As DataGridViewCell = CType(sender, DataGridView).Rows(e.RowIndex).Cells(e.ColumnIndex)
    
            cell.Value = Nothing
    
        End Sub
    

    Friday, September 09, 2011 12:46 AM
  • Private Sub DataGridView1_CellValidating(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellValidatingEventArgs) Handles DataGridView1.CellValidating
    
            Dim cell As DataGridViewCell = CType(sender, DataGridView).Rows(e.RowIndex).Cells(e.ColumnIndex)
    
            cell.Value = Nothing
    
        End Sub
    


    Hi,

    Set the value=string.empty. i hope it will do it.

    Regards,

    A.Murugan


    If it solved your problem,Please click "Mark As Answer" on that post and "Mark as Helpful". Happy Programming!
    Friday, September 09, 2011 2:32 AM
  • Hi,

    Does not work. I think its because its not the cell which contains the string value, but the DataGridViewTextBoxColumn control which is in editing mode inside that cell. I dont know how to get a reference to this control, which could allow to empty the cell. (Was doable in VB6)

    Friday, September 09, 2011 4:11 PM
  • Keboo,

    You can get a reference to the cell using the code i posted above.  i.e.

    Dim cell As DataGridViewCell = CType(sender, DataGridView).Rows(e.RowIndex).Cells(e.ColumnIndex)

    Since you want your code to execute after edit mode, try placing this code in the Validated event, not the Validating event. 

    Hope this helps.

     

     

    Saturday, September 10, 2011 12:47 PM
  • Hi Kéboo,

    What do you mean "Does not work"? Do you get any errors or exceptions?

    In addition, for "how to get a reference to this control, which could allow to empty the cell", do you mean how to get the the focused cell value? If so, AnRoN_P's suggestion is helpful. Please have a try and let us know the situation on your side.

    More information for DataGridView.CellValidating Event and DataGridView.CellValidated Event:

    http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.cellvalidating.aspx
    (DataGridView.CellValidating Event)

    http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.cellvalidated.aspx
    (DataGridView.CellValidated Event)

    Have a nice day.

    Best regards


    Liliane Teng [MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Monday, September 12, 2011 7:26 AM
  • Hello,

    The code suggested works in the Validated event, but thats not the effect I need. I want to detect an invalid value during Validating() and STAY in edit mode and erase the invalid value. Or perhaps change the value in the Validated event, but RETURN in edit mode. Can't find anything to do that. All the edit mode related properties of the grid are read-only.

     

     

    Monday, September 12, 2011 4:20 PM
  • Hi Keboo,

    I think this is what you are after.  Give it a go and let us know how you went.

     Private Sub DataGridView1_CellValidating(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellValidatingEventArgs) Handles DataGridView1.CellValidating
    
            Dim DGV As DataGridView = CType(sender, DataGridView)
            Dim cell As DataGridViewTextBoxCell = DGV.Rows(e.RowIndex).Cells(e.ColumnIndex)
    
            If cell.IsInEditMode Then
    
                'in this example, a cell value is considered invalid if it contains the word "invalidvalue"
                If CType(cell.Value, String) = "invalidvalue" Then
    
                    MessageBox.Show("Cell value is invalid", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
                    e.Cancel = True
    
                End If
    
            End If
    
        End Sub

    For you reference:

    http://msdn.microsoft.com/en-us/library/ykdxa0bc.aspx



    • Edited by AaRoN_P Tuesday, September 13, 2011 12:02 AM
    Tuesday, September 13, 2011 12:00 AM
  • Does the CellValidating event fire without a row change, I've never seen that done.

    Do you know how to debug with breakpoints.

    Otherwise rightclick on the first row in your event and select set breakpoint. Than click run (F5)

     


    Success
    Cor
    Tuesday, September 13, 2011 5:35 AM
  • Cor,

    Yeah CellValidating fires whenever a cell loses input focus. 

    Tuesday, September 13, 2011 5:43 AM
  • Aaron,

    You are right, I tested it, (had to make some small changes to your code). 

    Try to set Option Strict On in your Tools VB options.

    (Also I got with your sample the previous value)

    Sample partially in VB10SP1 if needed add byval

    Public Class Form1
        Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
            Dim dt As New DataTable
            Dim dc1 As New DataColumn
            Dim dc2 As New DataColumn
            dt.Columns.Add(dc1)
            dt.Columns.Add(dc2)
            For i = 0 To 3
                dt.Rows.Add(dt.NewRow)
                dt.Rows(i)(1) = CStr(i)
            Next
            dt.Rows(0)(0) = "Liliane"
            dt.Rows(1)(0) = "John"
            dt.Rows(2)(0) = "Armin"
            dt.Rows(3)(0) = "Ken"
            DataGridView1.DataSource = dt
        End Sub
        Private Sub DataGridView1_CellValidating(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellValidatingEventArgs) Handles DataGridView1.CellValidating
            Dim DGV As DataGridView = CType(sender, DataGridView)
            Dim cell As DataGridViewTextBoxCell = CType(DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex), DataGridViewTextBoxCell)
            	If cell.IsInEditMode Then
                           If CStr(e.FormattedValue) = "Cor" Then
                    MessageBox.Show("Cell value is invalid", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
                    e.Cancel = True
                End If
            End If
        End Sub
    End Class
    


     


    Success
    Cor


    Tuesday, September 13, 2011 6:29 AM
  • See the comment in the code sample. In this case if the cell does not contain a valid Integer, then I want to erase the fautly entry and remain in edit mode.

      Private Sub DataGridView2_CellValidating(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellValidatingEventArgs) Handles DataGridView2.CellValidating
        Dim DGV As Windows.Forms.DataGridView = CType(sender, Windows.Forms.DataGridView)
        Dim cell As DataGridViewTextBoxCell = DirectCast(DGV.Rows(e.RowIndex).Cells(e.ColumnIndex), DataGridViewTextBoxCell)
    
        Dim str As String = e.FormattedValue.ToString()
        Dim i As Integer = Integer.MinValue
    
        If Int32.TryParse(str, i) = False Then
          e.Cancel = True
          cell.Value = "" ' <----- does not work
    
        End If
      End Sub
    

     

    Tuesday, September 13, 2011 12:13 PM
  • Yeah by calling e.Cancel you are effectively preventing the code from getting past the Validating event of the cell, which means you cant do anything until a valid input has been entered (you can press ESC to exiting edit mode of course).

    Do you really need to clear the contents of the entire cell?  Perhaps it may be better to inform the user that the cell must be a valid integer and have them correct the value e.g. using a messagebox as in the example.  It may be irritating if the user has entered a large integer in there (say a bank account number), and accidently added a letter at the end, only to find that they have to re-input the whole number all over again for a trivial mistake (esspecially if you're like me and cant remember your account numbers off the top of your head!).

    I think you may have to look outside the validating event to get the effect your after, but i was struggling trying to find an alternative that allows you to cancel the event and have the application re-enter edit mode of the invalid cell, as you want.

     

    • Marked as answer by RebootUniverse Tuesday, September 13, 2011 4:46 PM
    Tuesday, September 13, 2011 1:01 PM
  • Try it by changing like this in my sample

    Public Class Form1
        Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            Dim dt As New DataTable
            Dim dc1 As New DataColumn
            Dim dc2 As New DataColumn
            dt.Columns.Add(dc1)
            dt.Columns.Add(dc2)
            For i = 0 To 3
                dt.Rows.Add(dt.NewRow)
                dt.Rows(i)(1) = CStr(i)
            Next
            dt.Rows(0)(0) = "Liliane"
            dt.Rows(1)(0) = "John"
            dt.Rows(2)(0) = "Armin"
            dt.Rows(3)(0) = "Ken"
            DataGridView1.DataSource = dt
        End Sub
        Private Sub DataGridView1_CellValidating(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellValidatingEventArgs) Handles DataGridView1.CellValidating
            Dim DGV As DataGridView = CType(sender, DataGridView)
            Dim cell As DataGridViewTextBoxCell = CType(DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex), DataGridViewTextBoxCell)
            If cell.IsInEditMode Then
                If CStr(e.FormattedValue) = "Cor" Then
                    MessageBox.Show("Cell value is invalid", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
                    DataGridView1.CancelEdit()
                End If
            End If
        End Sub
    End Class
    



    Success
    Cor
    • Marked as answer by RebootUniverse Tuesday, September 13, 2011 1:56 PM
    Tuesday, September 13, 2011 1:40 PM
  • >Do you really need to clear the contents of the entire cell?

    I am converting a legacy VB6 program which did that, so I am trying to provide the same functionnality. I dont want to tell the customer "by the way its not possible to do that now in VB.NET".

    > but i was struggling trying to find an alternative

    So am I. But its not critical. Would just be nice. Maybe provide a "ReplaceValue" property in DataGridViewCellValidatingEventArgs, in the next version of the framework ?

    Tuesday, September 13, 2011 1:49 PM
  • It works. Thanks !
    Tuesday, September 13, 2011 1:58 PM
  • Keboo,

    Don't forget to give Aaron helpful points which leads to this snippet. 

    I did already

     


    Success
    Cor
    Tuesday, September 13, 2011 4:34 PM
  • Sorry I didn't knew this was possible. Millions of Mark to everyone !

    Tuesday, September 13, 2011 4:47 PM
  • Thanks guys.

    Good luck with your application Keboo.

    Tuesday, September 13, 2011 10:58 PM