是否有可能使DataGridView,DataGridColumn,DataGridCell模仿excel中的特定行为?

时间:2011-08-22 16:55:19

标签: visual-studio-2008 datagridview datagridcolumn datagridcell

技术:Visual Studio .NET 2008

我想知道是否有人知道强制数据网格视图中的列与Excel类似行为的方法。

目前,这就是数据的样子:

A) 123456789.02211

我希望看到的是

B) 123,456,789.02

然而,问题是,我希望数据在不使用时看起来像“B”(没有焦点,鼠标不在单元格中),我希望数据在使用时看起来像“A”。 (细胞有焦点,而不是整个专栏。)

如果我不能做特定细胞,那没关系。如果它的宽度与“当dataGridview具有焦点时,所有数据看起来像A,我可以处理它。

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

您需要查看DataGridView的CellBeginEditCellEndEdit事件。 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" };
    }
}

CellBeginEditCellEndEdit事件都具有EventArg属性,您可以使用这些属性来确定是否(和/或如何)格式化单元格。我的示例使用e.ColumnIndex属性来确保我的日期列没有格式化。

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