sam
sam

Reputation: 2606

Validate Date entered into a DataGridView

I am trying to validate an entered Date value in a DataGridViewCell by users and if the value does not match the a specific scheme, it should give the user a message like

entered value should match dd/MM/yyyy format

I tried below code on CellValidating event

private void DGV_PatientSessions_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
    if (DGV_PatientSessions.Columns[e.ColumnIndex].Name == "DGV_PatientSessions_Date")
    {
        string DateValue;
        DateTime DateFormated;
        DateValue = DGV_PatientSessions.CurrentRow.Cells["DGV_PatientSessions_Date"].Value.ToString();
        if (DateTime.TryParseExact(DateValue, "dd/MM/yyyy", new CultureInfo("ar-SY"), DateTimeStyles.None, out DateFormated))
        {
            MessageBox.Show("done");
        }
    }
}

but I still get message error below

enter image description here

I tried to use regex which not recommended as I found when I searched but it wont work

string DateFormat;
DateFormat = DGV_PatientSessions.CurrentRow.Cells["DGV_PatientSessions_Date"].Value.ToString();
if(Regex.IsMatch(DateFormat, @"(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\d\d$"))
{
    MessageBox.Show("done");
}
else
{
    MessageBox.Show("value should match dd/MM/yyyy format);
}

Upvotes: 1

Views: 1764

Answers (1)

C-Pound Guru
C-Pound Guru

Reputation: 16368

You need to cancel the edit if the data entered is not valid using e.Cancel = true;:

private void DGV_PatientSessions_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
    if (DGV_PatientSessions.Columns[e.ColumnIndex].Name == "DGV_PatientSessions_Date")
    {
        string DateValue;
        DateTime DateFormated;
        DateValue = DGV_PatientSessions.CurrentRow.Cells["DGV_PatientSessions_Date"].Value.ToString();
        if (DateTime.TryParseExact(DateValue, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateFormated))
        {
            MessageBox.Show("done");
        } 
        else 
        {
            MessageBox.Show("value should match dd/MM/yyyy format");
            e.Cancel = true; // The important part
        }
    }
}

Upvotes: 1

Related Questions