在 asp.net c# 中为动态 gridview 单元格设置货币

Set currency for dynamic gridview cells in asp.net c#

我有一个动态网格视图,需要为某些列应用格式设置。

代码:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            for (int i = 0; i < GridView1.HeaderRow.Cells.Count; i++)
            {
                string strHeader = GridView1.HeaderRow.Cells[i].Text;
                List<string> lstCurrency = new List<string>() { "Price", "Amount" };
                bool checkAmount = lstCurrency.Exists(o => strHeader.Equals(o));
                if (checkAmount)
                {
                    e.Row.Cells[i].Text = String.Format("{0:C2}", e.Row.Cells[i].Text);
                }
            }
        }
    } 

如果 gridview 列 header 文本包含 PriceAmount,则需要应用货币格式,上面的代码不起作用。

如有错误请指正

您尝试过解析该值吗?根据您的要求使用 Int 或 Decimal。

e.Row.Cells[i].Text = String.Format("{0:C2}", Int32.Parse(e.Row.Cells[i].Text));

您需要将字符串 e.Row.Cells[i].Text 转换为 decimal:

e.Row.Cells[i].Text = String.Format("{0:C2}", Convert.ToDecimal(e.Row.Cells[i].Text));