DataGridView Numeric Only Cell?

前端 未结 8 591
广开言路
广开言路 2021-01-06 07:33

I am new to winforms..I am trying to set two column of DataGridView to Numeric Only.. I do not want user to be able to type anything into a cell unless its a natural number

相关标签:
8条回答
  • 2021-01-06 07:58
    Private Sub DataGridView1_EditingControlShowing(ByVal sender As Object, ByVal e As         System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles DataGridView1.EditingControlShowing
            AddHandler CType(e.Control, TextBox).KeyPress, AddressOf TextBox_keyPress
     End Sub
     Private Sub TextBox_keyPress(ByVal sender As Object, ByVal e As KeyPressEventArgs)
            If Char.IsDigit(CChar(CStr(e.KeyChar))) = False Then e.Handled = True
            If Not (Char.IsDigit(CChar(CStr(e.KeyChar))) Or e.KeyChar = ".") Then e.Handled = True
            If e.KeyChar = " "c Then e.Handled = False
      End Sub
    
    0 讨论(0)
  • 2021-01-06 08:04

    If data type validation is only concern then you can use CellValidating event like this

        private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            //e.FormattedValue  will return current cell value and 
            //e.ColumnIndex & e.RowIndex will rerurn current cell position
    
            // If you want to validate particular cell data must be numeric then check e.FormattedValue is all numeric 
            // if not then just set  e.Cancel = true and show some message 
            //Like this 
    
            if (e.ColumnIndex == 1)
            {
                if (!IsNumeric(e.FormattedValue))  // IsNumeric will be your method where you will check for numebrs 
                {
                    MessageBox.Show("Enter valid numeric data");
                    dataGridView1.CurrentCell.Value = null;
                    e.Cancel = true;
    
                }
    
            }
    
        }
    
    0 讨论(0)
提交回复
热议问题