2016-09-07 67 views
1

我是C#开发新手。这个可编辑的DataGridView有5列,最后一列允许使用小数。C#DataGridView单元格不允许小数

但我的问题是它如何只允许整数。 我希望你们能回答我这个问题

private void productionStockDataGridViewEcs_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e) 
    { 
     e.Control.KeyPress += 
     new KeyPressEventHandler(Control_KeyPress); 
    } 

private void Control_KeyPress(object sender, KeyPressEventArgs e) 
{ 
    int column = productionStockDataGridViewEcs.CurrentCellAddress.X; 
    int row = productionStockDataGridViewEcs.CurrentCellAddress.Y; 
    if (column == 4) 
    { 
     AllowDecimal(productionStockDataGridViewEcs.Rows[row].Cells["Quntity"], e, 10, 3); 
    } 

} 

private static void AllowDecimal(Control control, KeyPressEventArgs e, int noOfIntegers, int noOfPrecisions) 
     { 
      string decimalSeparator = Thread.CurrentThread.CurrentCulture.NumberFormat.CurrencyDecimalSeparator; 

      if ((47 < e.KeyChar && e.KeyChar < 58) || e.KeyChar == 8 || e.KeyChar.ToString() == decimalSeparator) 
      { 
       if (e.KeyChar.ToString() == decimalSeparator && control.Text != "") 
       { 
        if (control.Text.Contains(decimalSeparator)) 
        { 
         e.Handled = true; 
        } 
        else 
        { 
         CheckLengthForDecimal(control, e, noOfIntegers, noOfPrecisions);   //when double only ok 
        } 
       } 
       else 
       { 
        CheckLengthForDecimal(control, e, noOfIntegers, noOfPrecisions);   //when double only ok 
       } 
      } 
      else 
      { 
       e.Handled = true; 
      } 
     } 


private static void CheckLengthForDecimal(DataGridViewCell cell, KeyPressEventArgs e, int noOfIntegers, int noOfPrecisions) 
     { 
      TextBox textBox = new TextBox(); 
      textBox.Text = cell.Value.ToString(); 
      int cursorPosistion = textBox.SelectionStart; 
      string decimalSeparator = Thread.CurrentThread.CurrentCulture.NumberFormat.CurrencyDecimalSeparator; 

..................... 
} 

回答

0

试试这个,

AllowDecimal(productionStockDataGridViewEcs.EditingControl, e, 10, 3); 

为了您的例子中,你使用的DataGridView细胞productionStockDataGridViewEcs.Rows[row].Cells["Quntity"]AllowDecimal。将productionStockDataGridViewEcs.EditingControl设置为AllowDecimal方法

+0

是的,它的工作原理,谢谢 – Joy16

相关问题