ImGreg
ImGreg

Reputation: 2993

DataGridView C# Edit Mode Value Formatting After Edit

I have a datagridview in a C# Winform project. This datagridview is used to insert values into a database. Each column matches up to a corresponding db column.

One of the columns is a DateTime column. I want to 'validate' this date to ensure it is in the proper format. Ideally, you would leave the cell and it would convert it to a date time format that I choose.

I have used a series of events to attempt creating this functionality but have been having problems. The problem that I keep having is that when the event fires, the value has not been stored in the cell yet. Therefore, when I do something like this for example:

private void Grid_Modify_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
    if (Grid_Modify.Columns[e.ColumnIndex].Name == "DateTime")
    {
        Grid_Modify[e.ColumnIndex, e.RowIndex].Value = 
           Convert.ToDateTime(Grid_Modify[e.ColumnIndex, e.RowIndex].Value).ToString("YYYY-MM-DD hh:mm:ss");
    }
}

Problem is, the value it is converting to a datetime is the original cell value -- not the new value I just entered. I assume this is because the event is firing before the cell value is being updated.

Question is: What is the best way of formatting the date when I change its value?

The other events I have tried are: CellLeave, CellValueChanged, CellValidated, and CellEndEdit.

NOTE: CellValueChanged event was the only event that actually could get the new cell value, however, it gets caught in an infinite loop when I change the value within the eventhandler.

Upvotes: 0

Views: 2322

Answers (1)

Brad Rem
Brad Rem

Reputation: 6026

The simplest would be to go back to CellValueChanged event handler and use a global variable to avoid your infinite loop:

 private bool _inCellValueChanged = false;

Then, in CellValueChanged:

if (!_inCellValueChanged && Grid_Modify.Columns[e.ColumnIndex].Name == "DateTime") 
{ 
    _inCellValueChanged = true;        
    Grid_Modify[e.ColumnIndex, e.RowIndex].Value = Convert.ToDateTime(Grid_Modify[e.ColumnIndex, e.RowIndex].Value).ToString("YYYY-MM-DD hh:mm:ss");
    _inCellValueChanged = false; 
} 

Upvotes: 4

Related Questions