C# 如何在DataGridView单元格中制作格式掩码?
我需要在单元格中设置格式/掩码,以防止用户输入不相关的数据。 列单元格包含日期值,如C# 如何在DataGridView单元格中制作格式掩码?,c#,datagridview,datagridcell,C#,Datagridview,Datagridcell,我需要在单元格中设置格式/掩码,以防止用户输入不相关的数据。 列单元格包含日期值,如“MM/YYYY”,但不包含日期值 我尝试了以下定义,但没有成功: dataGridView1.Columns[0].DefaultCellStyle.Format = "##/####" // || dd/yyyy 此外,我还尝试转到DataGridView的属性,并从中定义Format。用于格式化的方法。这里可能会发生一些问题。请确保: 基础数据的类型为DateTime和非类型为string。类型strin
“MM/YYYY”
,但不包含日期值
我尝试了以下定义,但没有成功:
dataGridView1.Columns[0].DefaultCellStyle.Format = "##/####" // || dd/yyyy
此外,我还尝试转到
DataGridView
的属性,并从中定义Format
。用于格式化的方法。这里可能会发生一些问题。请确保:
DateTime
和非类型为string
。类型string
将不会按预期应用格式。(参见下面示例中的第1列和第2列。)DataGridViewTextBoxCell.Style.Format设置为与所需格式不同的格式。这将覆盖列格式。(参见下面示例中的第3列。)
示例
this.dataGridView1.ColumnCount = 4;
this.dataGridView1.RowCount = 1;
this.dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
DateTime date = DateTime.Now;
this.dataGridView1[0, 0].Value = date;
this.dataGridView1[1, 0].Value = date.ToString();
this.dataGridView1[2, 0].Value = date.ToString("MM/yyyy");
this.dataGridView1[3, 0].Value = date;
this.dataGridView1[3, 0].Style.Format = "MM/yyyy";
this.dataGridView1.Columns[0].DefaultCellStyle.Format = "dd/yyyy";
this.dataGridView1.Columns[1].DefaultCellStyle.Format = "dd/yyyy";
this.dataGridView1.Columns[2].DefaultCellStyle.Format = "dd/yyyy";
this.dataGridView1.Columns[3].DefaultCellStyle.Format = "dd/yyyy";
从输出中可以看到:
列[0]
包含一个日期时间
,格式正确为“dd/yyyy”
列[1]
包含一个字符串
,不能重新格式化为“dd/yyyy”
列[2]
包含格式化的字符串
,无法重新格式化为“dd/yyyy”
列[3]
包含一个日期时间
,格式由单元格格式“MM/yyyy”
覆盖要纠正这些问题,只需使用
DateTime
对象而不是任何string
表示来设置单元格值
如果您从某个外部源获取此数据,并且它已经是string
类型,您可以Parse
它,但是请注意DateTime
对象缺少的部分将被默认,如果没有原始的完整数据,您真的无能为力:
DateTime date = DateTime.Parse("10/2016");
Console.WriteLine("Output: {0}", date.ToString());
// Output: 10/1/2016 12:00:00 AM
验证
如果验证用户输入(并在编辑上丢失格式)是您的主要关注点,请考虑下面的验证方法来取消无效的编辑:
private void DataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
DateTime parsed;
if (!DateTime.TryParse(e.FormattedValue.ToString(), out parsed))
{
this.dataGridView1.CancelEdit();
}
}
与之配合使用
DataGridView.CellFormatting
事件处理程序重新应用格式。(请注意,这也不需要确保您的数据类型不是string
,但由于事件经常触发,成本更高。)您是否能够解决此问题?