DataGridView C# Edit Mode Value Formatting After Edit

非 Y 不嫁゛ 提交于 2019-12-12 03:19:38

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/9794990/datagridview-c-sharp-edit-mode-value-formatting-after-edit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!