货币文化格式不适用于DataGridView列

我有2个DataGridViews(DGV),并且我都有我要格式化的货币列。 我写的代码似乎在一个中工作,但在另一个中则不起作用。

两个DGV都以这种方式设置:数据首先加载到DataTable中。 然后BindingSource链接到此DataTable。 最后,DGV将这个BindingSource对象用于他们的数据。

我在表单的Load事件中使用以下代码来自定义两个DGV的货币列:

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

似乎将一个DGV中的列格式化为另一个DGV。 此外,它的NOT工作的DGV在其父窗体中甚至没有那么多的function代码..我检查了代码和DGV的属性,看看我是否在其他地方更改格式,但是我什么都没发现..

两个DGV加载数据的方式之间的唯一微小区别是,对于第一个DGV的DataTable(其中格式化工作),数据通过SELECT语句(通过我自己的函数)加载…在第二个DGV的DataTable(用于哪个格式化不起作用),我不从DB加载任何数据,而只是手动定义列(在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"); 

希望这有助于更多地诊断问题..

您不需要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"; } } } 

我希望它会有所帮助:)

(先前从问题回答)

在定义了两列之后添加了以下行,现在它可以工作:

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