Validating cell datagridview

Hi guys

How to lock a cell of datagridview to accept only numbers. Otherwise, to ignore the change.

Confused

  • You can use the CellValidating event to do this.

    I found the following example in the Microsoft docs and converted to COBOL:

    method-id dataGridView1_CellValidating final private.
           procedure division using by value sender as object e as type System.Windows.Forms.DataGridViewCellValidatingEventArgs.
           
              set dataGridView1::Rows[e::RowIndex]::ErrorText to ""
              declare newInteger as binary-long
    
             *> Don't try to validate the 'new row' until finished  
             *> editing since there 
             *> is not any point in validating its initial value. 
               if (dataGridView1::Rows[e::RowIndex]::IsNewRow) 
                  goback
               else
                  if not (type Int32::TryParse(e::FormattedValue::ToString, newInteger))
                     set e::Cancel to true
                     set dataGridView1::Rows[e::RowIndex]::ErrorText to "the value must be numeric"
                  end-if
               end-if
           end method.
          
    
  • Verified Answer

    Hi Chris,

    I had to make some adjustments because this code validates a blank line and I needed to validate the data change. Follows the working code.

    Thank you, I couldn’’t have done it without you
    Thank you, I couldn’’t have done it without you

        method-id dataGridView1_CellValidating final private.

           procedure division using by value sender as object e as type System.Windows.Forms.DataGridViewCellValidatingEventArgs.
               declare newInteger as binary-long
               declare x as float-short
               set dataGridView1::Rows[e::RowIndex]::ErrorText to ""
                       
               if e::ColumnIndex::Equals(10)
                  if not (type Int32::TryParse(e::FormattedValue::ToString, newInteger))
                     set e::Cancel to true
                     set dataGridView1::Rows[e::RowIndex]::ErrorText to "Erro no valor da coluna (TipoDoc)"
                     invoke type MessageBox::Show("Tipo de documento inválido. 1=CPF 2=CNPJ" "Visual Cobol.NET")
                  else
                     set x to type System.Convert::ToInt32(e::FormattedValue::ToString())
                     if x < 1 or > 2
                        set e::Cancel to true
                        set dataGridView1::Rows[e::RowIndex]::ErrorText to "Erro no valor da colunha (TipoDoc)"
                        invoke type MessageBox::Show("Tipo de documento inválido. 1=CPF 2=CNPJ" "Visual Cobol.NET")
                     end-if   
                  end-if
               end-if      
           end method.

    Thank you, I couldn't have done it without you.