【发布时间】:2013-06-27 15:07:16
【问题描述】:
我在C#/WinForms 应用程序中有一个DataGridView。
我想在单元格中输入日期。
如果用户输入01/01/2012,没关系,但是如果输入01012012,我有一个例外。
我能够使用CellValidating 事件验证输入。
不过,如果用户输入像 01012012 这样的日期,我想自动格式化,显然,我需要在 CellValidated 事件中执行此操作。
这是我的代码:
private void dataGridView_BadgeService_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
if (dataGridView_BadgeService.Columns[e.ColumnIndex].Name == "DateDebut" || dataGridView_BadgeService.Columns[e.ColumnIndex].Name == "DateFin")
{
String date = Convert.ToString(e.FormattedValue).Trim();
if (date.Length > 0)
{
try
{
DateTime _date;
if (DateTime.TryParse(date, out _date) == false)
{
if (DateTime.TryParseExact(date, "ddMMyyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out _date) == false)
{
MessageBox.Show("Merci de saisir une date, ou laissez cette zone vierge", "Action-Informatique", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
e.Cancel = true;
}
}
}
catch
{
MessageBox.Show("Merci de saisir une date, ou laissez cette zone vierge", "Action-Informatique", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
e.Cancel = true;
}
}
}
}
private void dataGridView_BadgeService_CellValidated(object sender, DataGridViewCellEventArgs e)
{
if (dataGridView_BadgeService.Columns[e.ColumnIndex].Name == "DateDebut" || dataGridView_BadgeService.Columns[e.ColumnIndex].Name == "DateFin")
{
String date = Convert.ToString(dataGridView_BadgeService.Rows[e.RowIndex].Cells[e.ColumnIndex].Value).Trim();
if (date.Length > 0)
{
try
{
DateTime _date;
if (DateTime.TryParse(date, out _date) == true)
{
dataGridView_BadgeService.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = _date.ToShortDateString();
}
else
{
if (DateTime.TryParseExact(date, "ddMMyyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out _date) == true)
{
dataGridView_BadgeService.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = _date.ToShortDateString();
}
}
}
catch
{
MessageBox.Show("Merci de saisir une date, ou laissez cette zone vierge", "Action-Informatique", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
}
}
我不知道为什么,但是如果我输入01012012,CellValidated 事件不会触发。我有一个 DataGridView Exception 关于 DateTime 的错误格式。
如何自动设置日期格式以避免出现此错误?
它说:“字符串未被识别为有效的日期时间”
非常感谢, 尼克斯
【问题讨论】:
-
这不是你的问题的答案,但你为什么不使用
dataGridView_BadgeService[e.RowIndex,e.ColumnIndex].Value而不是dataGridView_BadgeService.Rows[e.RowIndex].Cells[e.ColumnIndex].Value? -
我建议您花一些时间创建一个可重用的 DataGridViewDateTimePicker 控件:msdn.microsoft.com/en-us/library/7tas5c80.aspx
-
感谢您的回答,不过我想用 CellValidating 和 CellValidated 事件格式化 myslef。
-
什么是异常文本?请将其添加到您的问题中。
标签: c# .net datetime datagridview formatting