DataGridView - 如何仅设置单列的货币格式 [英] DataGridView - how to set the currency format for a single column ONLY
问题描述
我正在尝试将 datagridview 用于篮子.我已经让它显示客户的篮子,但我希望它显示价格列的货币,但我也有一个数量列,所以如果我将默认样式设置为货币,那么它会将两列更改为货币格式.
I am trying to use the datagridview for a basket. I have got it to display the basket of the customer but I would like it to display the currency for the Price column, but i have a Quantity column as well, so if I put the default style as currency then it will change both columns to the currency format.
我想要做的是将货币格式添加到价格列而不是数量列.
What I want to be able to do is add the currency format to the Price Column but not to the quantity column.
这是显示篮子的代码(Form_load)
Here is the code that displays the basket (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 文件中收集的.
The CustomerId is collected from a txt file that stores the CustomerId when they log in.
如果您还想查看更多代码,请发表评论,我会添加它.
If there is any more code that you would like to see then comment and i will add it.
这是我在表单上得到的内容,添加了货币作为样式.
This is what i get on the form with the currency added as the style.
推荐答案
您可以使用列的 DefaultCellStyle
属性的 Format
属性设置列的数据格式.
You can set format of data of a column using Format
property of its DefaultCellStyle
property of the column.
例如要使用当前文化为 DataGridView
的第二列使用货币格式,您可以使用这样的代码:
For example to use currency format for second column of a DataGridView
using current culture, you can use such code:
grid1.Columns[1].DefaultCellStyle.Format = "c";
或者例如使用特定的文化和特定的十进制数:
Or for example to use an specific culture and specific decimal numbers:
grid1.Columns[1].DefaultCellStyle.Format = "c2";
grid1.Columns[1].DefaultCellStyle.FormatProvider = CultureInfo.GetCultureInfo("en-GB");
更多信息
注意
如果您使用的是对象数据源,那么您也可以使用以下方法.基础相同,为列设置合适的格式,但使用属性:
If you are using an object data source, then you can use the following approaches as well. The Foundation is same, setting suitable format for the column, but using attributes:
这篇关于DataGridView - 如何仅设置单列的货币格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!