我正在尝试将 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# - DataGridView - 如何仅设置单列的货币格式-LMLPHP

最佳答案

您可以使用列的 Format 属性的 DefaultCellStyle 属性设置列的数据格式。
例如,要使用当前文化对 DataGridView 的第二列使用货币格式,您可以使用以下代码:

grid1.Columns[1].DefaultCellStyle.Format = "c";
或者例如使用特定的文化和特定的十进制数:
grid1.Columns[1].DefaultCellStyle.Format = "c2";
grid1.Columns[1].DefaultCellStyle.FormatProvider = CultureInfo.GetCultureInfo("en-GB");
更多信息
  • How to: Format Data in the Windows Forms DataGridView Control
  • Standard Numeric Format Strings - The Currency ("C") Format Specifier.

  • 注意
    如果您使用的是对象数据源,那么您也可以使用以下方法。基础是相同的,为列设置合适的格式,但使用属性:
  • DataAnnotations attributes for DataGridView in Windows Forms
  • Using custom attributes to control appearance of DataGridView columns
  • 关于c# - DataGridView - 如何仅设置单列的货币格式,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37026196/

    10-12 02:49
    查看更多