2012-12-25 33 views
2

我有2個DataGridViews(DGV),並在我有貨幣列,我想格式化。我正在寫的代碼似乎在一個工作,但不在另一個。貨幣文化格式不適用於DataGridView列

DGV的設置方式如下:首先將數據加載到DataTable中。 BindingSource然後鏈接到這個DataTable。最後,DGV使用這個BindingSource對象來處理他們的數據。

我用在窗體的Load事件下面的代碼同時定製DGVs'貨幣的列:

dataGridView.Columns[columnIndexHere].DefaultCellStyle.FormatProvider = CultureInfo.GetCultureInfo("de-DE"); 
dataGridView.Columns[columnIndexHere].DefaultCellStyle.Format = String.Format("c") 

似乎在一個DGV格式化兩列而不是其他。另外,其中不工作的DGV甚至在它的父窗體中都沒有那麼多功能代碼..我檢查了代碼和DGV的屬性,看看我是否在其他地方更改格式,但是我還沒有找到任何東西..

兩個DGV的加載數據的方式之間的輕微差異,對於第一個DGV的DataTable(格式化工作),通過SELECT語句加載數據(通過我自己的函數)...在第二個DGV的DataTable(格式化不起作用)中,我不加載任何來自數據庫的數據,而只是手動定義列(在DataTable中),因爲在這種情況下,用戶需要輸入數據..

任何線索爲什麼格式化不能在第二個DGV上工作?


編輯:添加更多信息:

爲了說明問題,我創建了一個新的C#的WinForms項目,僅增加了一個DataGridView的就可以了,下面的代碼添加到Load事件。即使該代碼,貨幣格式是不是正在做:

DataTable dataTable = new DataTable(); 
dataTable.Columns.Add("ColA"); 
dataTable.Columns.Add("ColB"); 
dataTable.Columns.Add("ColC"); 


dataTable.Rows.Add("John", 832.293, "London"); 
dataTable.Rows.Add("Alice", 32972978.20489, "Atlanta"); 
dataTable.Rows.Add("Mark", 9184793284739, "Tokyo"); 

BindingSource bindingSource = new BindingSource(); 
bindingSource.DataSource = dataTable; 

dataGridView1.DataSource = bindingSource; 

var format = (NumberFormatInfo)NumberFormatInfo.CurrentInfo.Clone(); 
format.CurrencySymbol = "Mn. "; 
dataGridView1.Columns["ColB"].DefaultCellStyle.FormatProvider = CultureInfo.GetCultureInfo("de-DE"); 
dataGridView1.Columns["ColB"].DefaultCellStyle.Format = String.Format("c"); 

希望這有助於診斷問題更多..

編輯2:找到了解決辦法!

新增定義兩列,並經過以下行,現在它的工作原理:

qBDFrmDTForDisplay.Columns["Combined Price"].DataType = Type.GetType("System.Decimal");

+0

如你所說,你手動定義的列。你可以分享你如何定義列來創建一個'DataTable'的代碼嗎? – spajce

+0

剛纔添加了更多信息...希望你們現在可以找出問題:) – Ahmad

回答

1

你不需要BindingSource列出所有的行,只是

dataGridView1.DataSource = dataTable

因爲您使用的是DataTable,請刪除此零件

dataGridView1.Columns [「ColB」]。DefaultCellStyle.Format = String.Format(「c」);

並嘗試使用CellFormatting事件。

private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) 
     { 
      if (e.ColumnIndex == 1) //Column ColB 
      { 
       if (e.Value != null) 
       { 
        e.CellStyle.Format = "c"; 
       } 
      } 
     } 

我希望這將有助於:)