Date Validation In Datagridview


Validate Date in particular cell

private void dgvBreakageExp_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
if (dgvBreakageExp.Columns[e.ColumnIndex].Name == "InvoiceDate" || dgvBreakageExp.Columns[e.ColumnIndex].Name == "ExpDate")
{
if (e.FormattedValue == null || e.FormattedValue.ToString() == "")
{
dgvBreakageExp[e.ColumnIndex, e.RowIndex].ErrorText = null;
return;
}
bool res = ValidateDate(e.FormattedValue.ToString());
if (res == false)
{
dgvBreakageExp[e.ColumnIndex, e.RowIndex].ErrorText = "Invalid Date,Date Should be('DD/MM/YYYY')";
dgvBreakageExp.EndEdit();
e.Cancel = true;
}
else
{
dgvBreakageExp[e.ColumnIndex, e.RowIndex].ErrorText = null;
e.Cancel = false;
}
}
}
//function for validate the date and return true or false
private bool ValidateDate(string date)
{
try
{
DateTime Test;
if (DateTime.TryParseExact(date, "dd/MM/yyyy", null, DateTimeStyles.None, out Test) == true)
{
return true;

}
 else
 {
 return false;
 }
 }
 catch
 {
 return false;
 }
 }

Advertisements

2 thoughts on “Date Validation In Datagridview

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s