DataGridView_CellFormatting - Formatting dates cells in column dates

Hello,

I currently have a grid that I want to check the date entered is valid and format it into a short date time. This seems to work OK except that the even keeps firing and wont allow the user to re-enter the value in the cell if incorrect.

Any suggestions (code below)

Thanks

private void CommissionDataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)

{

DataGridView dataGridView = (sender as DataGridView);

// Validates that the effective date entered

if (dataGridView.Columns[e.ColumnIndex].Tag.ToString() == "EffectiveDate")

{

if (e != null)

{

if (e.Value != null)

{

try

{

e.Value = DateTime.Parse(e.Value.ToString()).ToShortDateString();

e.FormattingApplied = true;

e.CellStyle.BackColor.ToKnownColor();

e.CellStyle.SelectionBackColor.ToKnownColor();

}

catch (FormatException)

{

e.FormattingApplied = true;

//Set the back ground to red so the user knows which cell

e.CellStyle.BackColor = Color.Red;

e.CellStyle.SelectionBackColor = Color.DarkRed;

MessageBox.Show(this,

RentSmartResourceManager.GetErrorMessage(ErrorMessages.InvalidDateEntered),

RentSmartResourceManager.GetDialogText(DialogText.HeaderCannotProceed),

MessageBoxButtons.OK,

MessageBoxIcon.Exclamation,

MessageBoxDefaultButton.Button1,

BaseUtility.GetRightToLeftAlignmentOption(null));

}

}

}

}

}



Answer this question

DataGridView_CellFormatting - Formatting dates cells in column dates

  • Sébastien Nunes

    I was able to achieve what I wanted to do using the Validating event handler.
  • DataGridView_CellFormatting - Formatting dates cells in column dates