【问题标题】:DataGridView - how to set the currency format for a single column ONLYDataGridView - 如何仅为单列设置货币格式
【发布时间】:2016-08-29 19:13:27
【问题描述】:

我正在尝试将 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 是从一个 txt 文件中收集的,该文件在他们登录时存储 CustomerId。

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

这是我在表格上添加的货币作为样式的内容。

【问题讨论】:

    标签: c# sql winforms tsql datagridview


    【解决方案1】:

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

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

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

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

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

    更多信息

    注意

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

    【讨论】:

      【解决方案2】:

      在设计时创建 DataGridView 列并将价格设置为仅格式化当前价格列 Datagridview tutorial

      Set DateTime format in DataGridView此链接视为设置日期格式,只需将日期格式更改为货币格式即可。

      【讨论】:

      • 我怎么能这样做,因为我以前没有这样做过?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-16
      • 1970-01-01
      相关资源
      最近更新 更多