0

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?

4

1 回答 1

1

您需要查看 DataGridViewCellBeginEditCellEndEdit事件。该CellBeginEdit事件将允许您格式化要编辑的单元格,并且该CellEndEdit事件将允许您在编辑完成后重置单元格的格式。

像这样:

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" };
    }
}

CellBeginEdit和事件都CellEndEdit具有 EventArg 属性,可用于确定是否(和/或如何)格式化单元格。我的示例使用该e.ColumnIndex属性来确保我的日期列未格式化。

您可能需要不同的格式化字符串,但这是您正在寻找的一般方法。

于 2011-08-22T17:49:58.637 回答