DataGridView上的日期未按预期格式化

时间:2011-04-11 16:46:18

标签: c# winforms datetime datagridview

我有一个列,它使用在列样式中设置的DateTime格式。

当用户输入日期时,它不会将其格式化为设置的样式。事实上,它没有对该领域做任何事情。我把胡言乱语放在那里,它需要它。

我在这里遗漏了什么吗?它不应该至少格式化日期或给出错误的日期格式错误吗?

1 个答案:

答案 0 :(得分:1)

尝试在datagridview上处理事件,获取文本输入并验证它是否是日期。我使用了事件CellEndEdit,但您可以随意选择。

enter image description here

private void CheckCellValue(object sender, DataGridViewCellEventArgs e)
{
        //my column index on the date is 0; modify yours as needed!
    if (e.ColumnIndex == 0 && e.RowIndex > -1 && e.RowIndex != dataGridView1.NewRowIndex)
    {
        //check whether this can be parsed as a date.
        string enteredVal = dataGridView1.CurrentCell.Value.ToString();
        DateTime dt;
        if (DateTime.TryParse(enteredVal, out dt))
        {
            dataGridView1.CurrentCell.Value = dt.ToString("dd-MMM-yyyy");
        }
        else
        {
            MessageBox.Show("Doh, that's not a date: " + enteredVal);
        }
    }
}