c# - 验证输入 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);
}
解决方案
如果输入的数据无效,您需要取消编辑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
}
}
}
推荐阅读
- ionic-framework - 离子 livereload 到根页面,但需要最后加载的页面
- google-sheets - 使用间接函数来引用查询函数的串联导入范围
- python - 在字符串上应用正则表达式模式列表并返回找到的匹配项
- facebook-graph-api - Facebook Graph API Explorer 没有给我位置
- ruby - 替换 URL 字符串中的主机名
- android - 包含 proteus 库时出错 - “android.support.v7.appcompat.R$layout”
- wpf - 在 WPF 中使用 DevExpress ChartControl 和数据网格
- nginx - Nginx反向代理后面的Qtorrent Web GUI未加载登录网页css
- ios - 填充集合视图内的图像视图
- python-3.x - PYQT Selected Combobox 项目应删除另一个组合框中的项目