简体   繁体   中英

How to set datagridview cell format when editing and after editing in C#?

The format of my DataGridView is correct when it is loaded. But when I try to edit the value and accepts it (enter or tab), the format is not applied.

I have added this CellEndEdit event hoping that it will correct the format after editing.

private void dataGridSales_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
{
    if (dataGridSales.CurrentCell.ColumnIndex == 2)
    {
        dataGridSales.Columns[2].DefaultCellStyle.Format = "N2";
    }
}

private void dataGridSales_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
    if (e.ColumnIndex == 2)
    {
        double price = Convert.ToDouble(dataGridSales.Rows[e.RowIndex].Cells[2].Value);
        dataGridSales.Columns[2].DefaultCellStyle.Format = "C2";

    }
}

or

private void dataGridSales_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
        dataGridSales.Columns[2].DefaultCellStyle.Format = "C2";
}

But instead it still doesn't show the correct format.

Cell value before editing:
编辑前的储存格值

Cell in edit mode:
单元格处于编辑模式

How can I change the format to N2 or to remove the currency sign when editing? You can see my CellBeginEdit event above, it changes the whole column format to N2 . I want to change only the selected cell.

Cell value after editing:
编辑后的储存格值

Column Default Cell Style: 列默认单元格样式

dataGridSales Events Code:

    //Change Total Amount when Price Column is changed
    private void dataGridSales_CellValueChanged(object sender, DataGridViewCellEventArgs e)
    {
        int count = 0;
        double total = 0;
        foreach (DataGridViewRow row in dataGridSales.Rows)
        {
            total += Convert.ToDouble(row.Cells[2].Value);
        }
        lblTotAmt.Text = "Total Amount: " + total.ToString("C2");
        lblTotItem.Text = "Total Items: " + count;
    }
    //Remove item/s
    private void dataGridSales_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e)
    {
        int count = 0;
        double total = 0;
        foreach (DataGridViewRow row in dataGridSales.Rows)
        {
            total += Convert.ToDouble(row.Cells[2].Value);
        }
        lblTotAmt.Text = "Total Amount: " + total.ToString("C2");
        lblTotItem.Text = "Total Items: " + count;
    }
    //Price Column check
    private void dataGridSales_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
    {
        e.Control.KeyPress -= new KeyPressEventHandler(colPrice_KeyPress);
        //e.Control.KeyDown -= new KeyEventHandler(dataGridSales_KeyDown);
        if (dataGridSales.CurrentCell.ColumnIndex == 2)
        {
            TextBox tb = e.Control as TextBox;
            if (tb != null)
            {
                tb.KeyPress += new KeyPressEventHandler(colPrice_KeyPress);
            }
            if (e.Control is TextBox)
            {
                cprice = e.Control as TextBox;
            }
        }
    }
    //Price Column keypress only accept numbers
    private void colPrice_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.')
        {
            e.Handled = true;
        }
        TextBox txtDec = sender as TextBox;
        if (e.KeyChar == '.' && txtDec.Text.Contains("."))
        {
            e.Handled = true;
        }
    }

    private void dataGridSales_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
    {
        if (dataGridSales.CurrentCell.ColumnIndex == 2)
        {
            dataGridSales.Columns[2].DefaultCellStyle.Format = "N2";
        }
    }

    private void dataGridSales_CellEndEdit(object sender, DataGridViewCellEventArgs e)
    {
        if (e.ColumnIndex == 2)
        {
            double price = Convert.ToDouble(dataGridSales.Rows[e.RowIndex].Cells[2].Value);
            dataGridSales.Columns[2].DefaultCellStyle.FormatProvider = CultureInfo.GetCultureInfo("en-PH");
            dataGridSales.Columns[2].DefaultCellStyle.Format = String.Format("C2");
            dataGridSales.Columns[2].ValueType = typeof(Double);
        }
    }

    //Double click on a cell to edit
    private void dataGridSales_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
    {
        if (e.ColumnIndex == 2)
        {
            dataGridSales.BeginEdit(true);
        }
    }

Your problem is that you're not specifying the culture on which the formatter should format. This should solve your problem.

private void dataGridSales_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
    if (e.ColumnIndex == 2)
    {
        double price = Convert.ToDouble(dataGridSales.Rows[e.RowIndex].Cells[2].Value);
            dataGridSales.Columns[2].DefaultCellStyle
                                    .FormatProvider = CultureInfo.GetCultureInfo("en-US");
            dataGridSales.Columns[2].DefaultCellStyle.Format = String.Format("c");

    }
}

Note that you should replace "en-US" with the culture code/index of your desired currency.

Edit:

You should also try to add the following code to a method that is run prior to data load:

dataGridSales.Columns[2].DefaultCellStyle.FormatProvider = CultureInfo.GetCultureInfo("en-US");
dataGridSales.Columns[2].DefaultCellStyle.Format = String.Format("c");
dataGridSales.Columns[2].ValueType = typeof(Double);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM