首页 > 解决方案 > 验证输入 DataGridView 的日期

问题描述

我正在尝试验证用户Date在 a 中输入的值DataGridViewCell,如果该值与特定方案不匹配,它应该给用户一条消息,例如

输入的值应匹配 dd/MM/yyyy 格式

CellValidating我在事件中尝试了以下代码

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

但我仍然在下面收到消息错误

在此处输入图像描述

我尝试使用我在搜索时发现的不推荐的正则表达式,但它不起作用

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

标签: c#winformsvalidationdatagridview

解决方案


如果输入的数据无效,您需要取消编辑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
        }
    }
}

推荐阅读