【问题标题】:Validate Date entered into a DataGridView验证输入 DataGridView 的日期
【发布时间】:2018-10-01 19:46:36
【问题描述】:

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

的消息

输入的值应匹配 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# winforms validation datagridview


    【解决方案1】:

    如果使用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
            }
        }
    }
    

    【讨论】:

    • 我试一试,现在我总是得到 else 部分,即使datagridview 中的单元格为空,我也无法输入数据,简而言之,验证总是错误的
    • @sam 抱歉,我没有仔细检查您的 DateTime 解析测试,看看您是否正确执行。如果你是,这就是你处理它的方式。我猜你不是,这将是一个完全不同的独立问题。
    • @sam 我编辑了我的答案以使用“CultureInfo.InvariantCulture”——看看这是否会有所不同。
    • 同样的问题没有改变
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-09
    • 1970-01-01
    • 2016-06-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多