c# - DataGridView - 如何仅为单个列设置货币格式

标签 c# sql winforms tsql 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 文件中收集的。

如果您还想看到更多代码,请发表评论,我会添加。

这是我在表单上得到的,并将货币添加为样式。 enter image description here

最佳答案

您可以使用列的 DefaultCellStyle 属性的 Format 属性设置列的数据格式。

例如,要使用当前文化为 DataGridView 的第二列使用货币格式,您可以使用这样的代码:

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

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

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

更多信息

注意

如果您使用的是对象数据源,那么您也可以使用以下方法。 Foundation 是相同的,为列设置合适的格式,但使用属性:

关于c# - DataGridView - 如何仅为单个列设置货币格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37026196/

相关文章:

wpf - 不同大小的WPF表单-设计模式与运行时模式

c# - azure 函数 - 如何安排可能取消的工作

sql - 从 CASE 语句分配给 T-SQL 变量

c# - 无法从 DoWork() 内部从 MySQL 数据库获取信息

php - MySQL:排序依据不正确

sql - 将 Excel 公式转换为 SQL

c# - 启动离线 ClickOnce 应用程序并等待退出

c# - WCF 身份验证服务

c# - 什么是最快的 sql 实现,如 'x%' 在 c# 集合中的键

c# - 让 Graphic 最初显示出来