2017-06-23 23 views
1

我有一個函數,將文本框的值格式化爲貨幣。我在Textbox Leave事件中做了這個。Datagridview文本框離開事件

private void txtSellingPrice_Leave(object sender, EventArgs e) 
{ 
    txtSellingPrice.Text = FormatCurrency(txtSellingPrice.Text); 
} 

例如,用戶輸入100,輸出將爲100美元。

我的問題是我將如何在datagridview單元格中執行它?我已經嘗試在編輯控制中添加離開事件。我也嘗試了DefaultCellStyle.Format =「C2」,這可以工作,但是當用戶改變當前值時,比如說$ 100.00改爲50.輸出應該是$ 50.00。謝謝。

+0

您應該考慮使用NumericBox而不是TextBox,並且在您的DataGrid中使用NumericColumn而不是TextColumn。數字特定的控制按照你想要的來設計。 –

+0

謝謝,但我認爲NumericBox是一個自定義控件。它在我的工具箱中不可用。我正在使用Visual Studio 2015.可用的是numericUpDown控件。 – Zhyke

+0

https://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.cellformatting(v=vs.110).aspx – Crowcoder

回答

0

最簡單的方法,將被分配一個BindingSource的DataGridView的你和的BindingList您BindingSoure。將顯示貨幣的列的默認單元格樣式格式設置爲C2。

如果你已經這樣做了,貨幣欄中任何添加/更改/刪除的單元格將自動被格式化。

但是,如果你不想使用BindingSource的,你必須做你自己的格式。使用事件DataGridViewCell.CellValidating和DataGridViewCell.CellFormating。

讓我們假設你有一個columnCurrency,爲要在格式C2被dislayed一個十進制值。 DefaultCellFormat被設置爲C2。

在驗證單元,檢查值實際上是一個十進制:

private void OnCellValidating(object sender, DataGridViewCellValidatingEventArgs e) 
{ 
    if (e.RowIndex == -1) return; 
    if (e.ColumnIndex == this.columnValue.Index) 
    { 
     decimal value; 
     e.Cancel = !Decimal.TryParse((string)e.FormattedValue, out value); 
    } 
} 

每當單元必須進行格式化,在e.Value格式化值:

private void OnCellFormatting(object sender, DataGridViewCellFormattingEventArgs e) 
{ 
    if (e.ColumnIndex == this.columnValue.Index) 
    { 
     if (e.Value == null) 
     { // show the Null value: 
      e.Value = e.CellStyle.NullValue; 
      e.FormattingApplied = true; 
     } 
     else 
     { // because validated I know value is a decimal: 
      decimal value = Decimal.Parse((string)e.Value); 
      e.Value = value.ToString(e.CellStyle.Format); 
      e.FormattingApplied = true; 
     } 

     // If desired apply other formatting, like background colouring etc 
    } 
} 

如果你不「不想用‘C2’作爲貨幣格式,並希望使用功能FormatCurrency你必須創建一個使用FormatCurrency格式化並設置DefaultCellStyle

的FormatProvider一個FormatProvider
private void OnCellFormatting(object sender, DataGridViewCellFormattingEventArgs e) 
{ 
    if (e.ColumnIndex == this.columnValue.Index) 
    { 
     ... (check for null value as described above) 
     else 
     { 
      e.Value = String.Format(e.Value, e.CellStyle.FormatProvider); 
      e.FormattingApplied = true;