2012-12-25 31 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"; 
       } 
      } 
     } 

我希望这将有助于:)