keep formatting in cell in datagridview c #

0

Good evening: I have a datagridview (dgv) where the "Price" column has the format "N2" defined in the DefaultCellStyle property of the dgv. When I change the value of the Price cell, the format is lost. For example, when I put 5 should be 5.00 and not 5. How can I do to maintain the format? Thanks

    
asked by Mario Escudero 08.08.2016 в 02:40
source

2 answers

2

You could apply the format to the value entered in the event CellEndEdit

private void dgv_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
    if (e.ColumnIndex == 0) {
        DataGridViewCell cell = dgv.Rows(e.RowIndex).Cells(e.ColumnIndex);
        cell.Value = Convert.ToDecimal(cell.Value).ToString("N2");
    }

}
    
answered by 08.08.2016 / 05:50
source
1

You can try something like this:

int num = 5;
float resultado;
resultado = formato(num);

    private static float formato(int numero)
    {
        String numformat = numero.ToString() + "." + "00";
        return float.Parse(numformat);
    }
    
answered by 08.08.2016 в 08:19