DataGridView – 如何仅为单个列设置货币格式

我正在尝试将datagridview用于购物篮。 我有它显示客户的篮子,但我希望它显示价格列的货币,但我也有一个数量列,所以如果我把默认样式作为货币,那么它将更改两列货币格式。

我想要做的是将货币格式添加到价格列,但不添加到数量列。

这是显示购物篮的代码(Form_load)

using (var con = new SqlConnection(connectionString)) { SqlDataAdapter dataadapter = new SqlDataAdapter( "select p.productname 'Product Name', b.productquantity 'Quantity', c.categoryname 'Category', p.price 'Current Price' " + "from basket b join products p on b.productid = p.productid " + "join Categories c on c.categoryid = p.categoryid " + $"where b.customerid = {CustomerId}", con); DataSet ds = new DataSet(); con.Open(); dataadapter.Fill(ds); con.Close(); dataGridView1.DataSource = ds.Tables[0].DefaultView; } 

CustomerId是从存储CustomerId的txt文件中收集的。

如果您想要查看更多代码然后发表评论,我将添加它。

这是我在表单上添加货币作为样式。 在此处输入图像描述

您可以使用列的DefalutCellStyle属性的Format属性设置列的数据Format

例如,要使用当前区域性为DataGridView第二列使用货币格式,您可以使用以下代码:

 grid1.Columns[1].DefaultCellStyle.Format = "c"; 

或者例如使用特定的文化和特定的十进制数:

 grid1.Columns[1].DefaultCellStyle.Format = "c2"; grid1.Columns[1].DefaultCellStyle.FormatProvider = CultureInfo.GetCultureInfo("en-GB"); 

更多信息:

  • 如何:在Windows窗体DataGridView控件中格式化数据
  • 标准数字格式字符串 – 货币(“C”)格式说明符。

在设计时创建DataGridView列并设置价格仅格式化当前价格列Datagridview教程

在DataGridView中设置DateTime格式此链接被视为设置日期格式,只需更改货币格式的日期格式。