您用于格式化的方法is a valid approach。这里可能会发生一些问题。请确保:
- 的基础数据为
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";
正如从输出中看到:
Columns[0]
包含DateTime
并正确格式为"dd/yyyy"
。
Columns[1]
包含string
,无法重新格式化为"dd/yyyy"
。
Columns[2]
包含格式化的string
,无法重新格式化为"dd/yyyy"
。
Columns[3]
包含DateTime
,格式化将被单元格格式"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
验证
如果验证用户输入(和丢失格式上进行编辑)是你的主要问题,请考虑以下方法进行验证,取消无效编辑:
加上
this answer使用
DataGridView.CellFormatting
事件处理程序重新申请您的格式
private void DataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
DateTime parsed;
if (!DateTime.TryParse(e.FormattedValue.ToString(), out parsed))
{
this.dataGridView1.CancelEdit();
}
}
。 (请注意,这也不利于确保您的数据类型不是string
,但是由于经常触发事件而导致成本更高)。
您是否能够解决该问题? – OhBeWise