Question

Technologies: Visual Studio .NET 2008

I'm wondering if anyone is aware of a way to force a column in a datagridview to behave similarily to Excel.

Currently, this is what the data looks like:

A) 123456789.02211

what I would like to see is

B) 123,456,789.02

However, the catch is, I want the data to look like "B" when not in use (no focus, mouse isn't in cell) and I want the data to look like "A" when in use. (Cell has focus, not the whole column.)

If I can't do the specific cell, that's fine. If it's as broad as "When the dataGridview has focus, all data looks like A, I can deal with that.

Any ideas?

Was it helpful?

Solution

You'll want to take a look at the DataGridView's CellBeginEdit and CellEndEdit events. The CellBeginEdit event will allow you to format the cell you're about to edit and the CellEndEdit event will allow you to reset the cell's format back after editing is complete.

Like this:

private void dataGridView1_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e) {
    if (e.ColumnIndex != indexOfMyDateColumn) {    // Don't custom format all columns.
        dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style = new DataGridViewCellStyle() { Format = "F5" };
    }
}

private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e) {
    if (e.ColumnIndex != indexOfMyDateColumn) {    // Don't custom format all columns.
       dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style = new DataGridViewCellStyle { Format = "N2" };
    }
}

Both the CellBeginEdit and the CellEndEdit events have EventArg properties that you can use to determine if (and/or how) you want to format your cells. My example uses the e.ColumnIndex property to ensure that my date column is not formatted.

You might need different formatting strings but this is the general approach you're looking for.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top