2016-10-11 25 views
0

我正在C#dot Net中開發一個銷售點應用程序,其中包含一個datagridview。在Datagridview中限制點(。)單元格的開始位置

我想限制datagridview的一些單元格值以下的東西。

  • 不要在單元格的開頭輸入一個點(「。」)(這確實是需要的)。
  • 請勿輸入任何字母或其他字符。 (我已經開發了這個,但需要一個改進的想法)
  • 只有輸入負數的數值。 (我已經開發了這個,但需要一個改進的想法)

指導我在這種情況下。

以下是我的代碼

private void Numeric_KeyPress(object sender, KeyPressEventArgs e) 
{ 
    if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.' && e.KeyChar != 46) 
    //if (!char.IsDigit(e.KeyChar) && e.KeyChar != '.') 
    { 
     e.Handled = true; 
    } 
    // only allow one decimal point 
    if ((e.KeyChar == '.') && ((sender as TextBox).Text.IndexOf('.') > -1) && ((sender as TextBox).Text.IndexOf('.') != 1)) 
    { 
     e.Handled = true; 
    } 
} 

    private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e) 
     { 
      e.Control.KeyPress -= new KeyPressEventHandler(Numeric_KeyPress); 
      if (dataGridView1.CurrentCell.ColumnIndex == 1) 
      { 
       TextBox tb = e.Control as TextBox; 
       if (tb != null) 
       {      
        tb.KeyPress += new KeyPressEventHandler(Numeric_KeyPress); 
       } 
      } 

} 
+0

你使用數據綁定嗎?並向我們​​展示您的代碼。 –

+0

謝謝亞歷山大。我用代碼更新了我的問題。 – Wajahat

+0

不同的文化用途是不同的分隔符整體和數字的一小部分(例如,俄語逗號)以及其他格式。因此,根據當前的用戶文化,拋出您的代碼並在用戶輸入後驗證輸入的值。 –

回答

0

最簡單的方法是處理CurrentCellDirtyStateChanged事件。

我正在使用正則表達式來驗證值。此代碼允許您只輸入包括負數的數字。

private void DataGridView_CurrentCellDirtyStateChanged(object sender, EventArgs e) 
{ 
    var cell = dataGridView.CurrentCell; 
    if (cell.ColumnIndex != 1) 
     return; 

    string value = cell.EditedFormattedValue.ToString(); 
    string pattern = @"^-$ | ^-?0$ | ^-?0\.\d*$ | ^-?[1-9]\d*\.?\d*$"; 

    if (Regex.IsMatch(value, pattern, RegexOptions.IgnorePatternWhitespace)) 
    { 
     dataGridView.CommitEdit(DataGridViewDataErrorContexts.Commit); 
    } 
    else 
    { 
     dataGridView.CancelEdit(); 
    } 
} 

注意:此代碼不允許用戶在自己的文化中輸入數字。

相關問題