【问题标题】:Currency format in DataGridView in windows applicationWindows应用程序中DataGridView中的货币格式
【发布时间】:2017-01-06 01:27:48
【问题描述】:

我无法在 DataGridView 上显示货币格式。 你们能看一下这段代码吗?

private void dataGridView1_DataBindingComplete(object sender,
                                   DataGridViewBindingCompleteEventArgs e)
{
    objPreview.dataGridView1.Columns["Debit"].DefaultCellStyle.Format = "c";
    objPreview.dataGridView1.Columns["Credit"].DefaultCellStyle.Format = "c";
}

【问题讨论】:

  • 您的数据源中DebitCredit 的数据类型是什么?
  • 如果你得到你想要的信息,不要忘记将答案标记为已接受...
  • 借记、贷记均为十进制类型
  • 能否在数据源分配前先分配格式
  • 这对你有用吗???

标签: c# datagridview formatting


【解决方案1】:

尝试添加这个

objPreview.dataGridView1.Columns["Debit"].ValueType = Type.GetType("System.Decimal")
objPreview.dataGridView1.Columns["Credit"].ValueType = Type.GetType("System.Decimal")

【讨论】:

  • 我需要货币格式。我希望这对我来说不是相关的代码。
【解决方案2】:

如果是 windows 窗体,则在将数据绑定到网格之前编写此代码...在窗体构造函数中如下所示...

public Form1()
{
   this.dataGridView1.Columns["UnitPrice"].DefaultCellStyle.Format = "c";
}

如果它的 ASP.Net 尝试类似DataFormatString="{0:c}"

<asp:BoundField HeaderText="Price/Unit" 
                DataField="UnitPrice" SortExpression="UnitPrice" 
                DataFormatString="{0:c}">
                    <ItemStyle HorizontalAlign="Right"></ItemStyle>

【讨论】:

  • 我觉得这和winform有关
  • 嗯 .. DefaultCellStyle 可能有助于做出决定
  • @V4Vendetta - 我为此更新了答案,他必须在绑定网格数据之前在构造函数中编写代码行...
  • 一个重要注意事项,当您使用这种格式时,分配给单元格的值也必须是数字类型,否则不会应用(在网格更加动态和值的情况下发生在我身上)被序列化为字符串并稍后恢复,我花了一些时间才意识到这发生在我身上)
【解决方案3】:

您能否检查(断点或其他)DataBindingComplete 事件是否已触发。所以至少我们知道不是这样

(已编辑) 所以如果它被解雇了,这可能会有所帮助

http://msdn.microsoft.com/en-us/library/k4sab6f9

也许通过创建一种新样式会有所帮助

【讨论】:

  • 事件正在触发,但 $ 符号未添加到值中。
  • 您应该等待 50 分才能获得评论特权,否则人们可能会拒绝投票,因为这不是任何答案。
【解决方案4】:

您也可以将它用于 Windows 窗体:(或 WPF 或 ASP 的等价物,...)

yourColumn.DefaultCellStyle.Format = "#,#";

// And add below if you want
yourColumn.DefaultCellStyle.NullValue= "0";

【讨论】:

    【解决方案5】:

    如果您已经将 DataSource 绑定到 DataGridView,则可以通过设置每个单元格格式来设置单元格样式:

    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
      row.Cells["Debit"].Style.Format = "c";
      row.Cells["Credit"].Style.Format = "c";  
    }
    

    确保您的值是数字。

    【讨论】:

      【解决方案6】:

      尝试将@Pranay Rana 建议的代码添加到 DataGridView 上的 CellFormatting 事件中:

      private void NameOfYourGridGoesHere_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
      {
          this.NameOfYourGridGoesHere.Columns["UnitPrice"].DefaultCellStyle.Format = "c";
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-10-29
        • 1970-01-01
        • 2010-09-24
        • 2018-04-01
        相关资源
        最近更新 更多