如何仅设置一个单元格的货币格式

How to set the currency format for one cell ONLY

我有包含两列(价格(int)和货币(nverchar))的数据库 table 价格列的单元格根据第二列(单元格)中的货币进行格式化。 例如: 在数据库中

价格 货币
12000 美元
20000 欧元

用户应该会在 DataGrid 中看到格式化的视图。例如:

价格 货币
12,000.00 美元 美元
20,000.00 欧元 欧元

我该怎么做?

I ​need to do this in Form_load or by a funk that will be called there. I mean: I need to check for all rows and if row[0].cells2 or row[1].cells[2]... contains 'usd' then i need change format the first cell of this row

这可能吗?

如果要设置grid的数据源,那么……也许……可以把这个丢到grids的CellFormating事件中。然而,应该清楚的是,在长 运行 中,单元格将被格式化很多次,而不是必要的。我认为我们可以做得更好。在 1) 用户更改 Currency 单元格,或 2) 新数据加载到网格中之前,我们无法“格式化”单元格。

第一部分很简单……连接网格 CellValueChanged 事件。如果更改的单元格值是 Currency 单元格……然后,检查“新”值并相应地格式化 Price 单元格。

这在用户更改 Currency 单元格值时起作用,但是,在加载数据时不起作用。因此,通过网格行的简单循环应该可以解决该问题。由于我们需要在两个不同的地方设置 Price 单元格格式,我建议创建一个采用 DataGridViewRow 并为给定行格式化“价格”单元格的方法。它可能看起来像……

private void FormatAmountCell(DataGridViewRow row) {
  if (!row.IsNewRow && row.Cells["Currency"].Value != null) {
    string currency = row.Cells["Currency"].Value.ToString();
    DataGridViewCell cellToFormat = row.Cells["Price"];
    switch (currency) {
      case "EUR":
        cellToFormat.Style.FormatProvider = CultureInfo.GetCultureInfo("en-GB");
        break;
      default:
        cellToFormat.Style.FormatProvider = CultureInfo.GetCultureInfo("en-US");
        break;
    }
  }
}

有了这个助手,我们就可以在网格连接 CellValueChanged 事件中使用它。

private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e) {
  FormatAmountCell(dataGridView1.Rows[e.RowIndex]);
}

此外,一个循环遍历网格行并设置每个“价格”单元格格式的小方法。我们将在数据加载到网格后调用它。

private void FormatAmountCellForAllRows() {
  foreach (DataGridViewRow row in dataGridView1.Rows) {
    FormatAmountCell(row);
  }
} 

将所有这些放在一起进行测试可能看起来像……

DataTable GridTable;

public Form1() {
  InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e) {
  dataGridView1.CellValueChanged += new DataGridViewCellEventHandler(dataGridView1_CellValueChanged);
  GridTable = GetData();
  dataGridView1.DataSource = GridTable;
  dataGridView1.Columns["Price"].DefaultCellStyle.Format = "c";
  FormatAmountCellForAllRows();
}

private DataTable GetData() {
  DataTable dt = new DataTable();
  dt.Columns.Add("Price", typeof(decimal));
  dt.Columns.Add("Currency", typeof(string));
  Random rand = new Random();
  for (int i = 0; i < 10; i++) {
    dt.Rows.Add(rand.NextDouble() * 100, (rand.Next(2) == 0 ? "USD" : "EUR"));
  }
  return dt;
}

现在您可以睡个好觉了,因为您知道格式化绝不会不必要地完成。