2016-09-07 97 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

相關問題