vb.net 格式化数据表的列以显示货币

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17798792/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 14:20:55  来源:igfitidea点击:

Formatting a datatable's column to show currency

vb.netgridviewdatatabledynamic-columnscurrency-formatting

提问by Thomas Holladay

I am inputing a datatable into a gridview to show several different charges from this past year. I want the charges in the gridview to appear in currency format but I would also like to be able to sort the columns when the headers are clicked.
I can get the format to be currency easily if the columns are of the type string ex. dim dt as DataTable dt.Columns.Add("ChargeField ", System.Type.GetType("System.String"))

我正在将数据表输入到 gridview 中,以显示过去一年中的几种不同费用。我希望 gridview 中的费用以货币格式显示,但我也希望能够在单击标题时对列进行排序。
如果列的类型为字符串 ex,我可以轻松地将格式设为货币。将 dt 作为 DataTable dt.Columns.Add("ChargeField ", System.Type.GetType("System.String"))

but the sorting doesn't work right when it is a string

但是当它是一个字符串时排序不起作用

I sort by using this code dt.DefaultView.Sort = ChargeField & " " & ASC

我使用此代码进行排序 dt.DefaultView.Sort = ChargeField & " " & ASC

Sorting does work when the columns are of type double ex. dt.Columns.Add("ChargeField ", System.Type.GetType("System.Double"))

当列的类型为 double ex 时,排序确实有效。dt.Columns.Add("ChargeField", System.Type.GetType("System.Double"))

but then it isn't in currency format.

但它不是货币格式。

Is there a way to make the datatable/Gridview have a double/decimal column that shows its values as currency? If not, is there a better way to accomplish what I am trying to do?

有没有办法让数据表/Gridview 有一个双/十进制列,将其值显示为货币?如果没有,有没有更好的方法来完成我想要做的事情?

回答by rwisch45

Add the columns as double (just like you said in your post) so that they will sort properly.

将列添加为双列(就像您在帖子中所说的那样),以便它们正确排序。

dt.Columns.Add("ChargeField ", System.Type.GetType("System.Double"))

Then you can do this to format all the columns in a data grid view as currency:

然后,您可以执行此操作以将数据网格视图中的所有列格式化为货币:

DataGridView1.DataSource=dt
DataGridView1.DefaultCellStyle.Format = "c"

Alternatively, you can do it for individual columns:

或者,您可以为单个列执行此操作:

DataGridView1.DataSource=dt
DataGridView1.Columns("ChargeField").DefaultCellStyle.Format = "c"

For a Gridview, you can use DataFormatString. This MSDN pagemight help, as well as this MSDN forum postand this ASP.net forum post

对于 Gridview,您可以使用 DataFormatString。这个 MSDN 页面可能有帮助,还有这个 MSDN 论坛帖子这个 ASP.net 论坛帖子

<Columns>
    <asp:BoundField DataField="ChargeField" DataFormatString = "{0:c}" />
</Columns>