Click here to Skip to main content
14,979,508 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
During the population of the datagridview dgv column TCharge is formatted to 2 decimal places using the following code:
C#
dgv.Columns["TCharge"].DefaultCellStyle.Format = "N2";

Now, I want the values in column CValue to be formatted based on the true/false flag in column TCash. So I have placed a code in the cellformatting event. Is this ok, please? I ask because the program seems to go into a loop forever...

Thanks

C#
private void dgv_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (dgv.Columns[e.ColumnIndex].Name.ToLower() == "cvalue")
            {
                if (e.Value != null)
                {
                    if (bool.Parse(dgv["TCash", e.RowIndex].Value.ToString()) == true)
                    {
                        dgv.Columns["CValue"].DefaultCellStyle.Format = "N2";
                    }
                    else
                    {
                        dgv.Columns["CValue"].DefaultCellStyle.Format = "N1";
                    }
                }
            }
        }
Posted
Updated 29-Sep-11 3:47am
v2

1 solution

I would just change the style for the cell rather than the entire column.

C#
if (bool.Parse(dgv["TCash", e.RowIndex].Value.ToString()) == true)
{
    e.CellStyle.Format = "N2";
}
else
{
    e.CellStyle.Format = "N1";
}
   
Comments
arkiboys 29-Sep-11 17:06pm
   
Thanks

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900