简体   繁体   English

DataGridView上的日期格式不符合预期

[英]date on DataGridView not formatting as expected

I have a column that uses the DateTime format that was set in the column styles. 我有一列使用在列样式中设置的DateTime格式。

When a user enters a date, it's not formatting it to the style that it is set to. 用户输入日期时,不会将其格式化为所设置的样式。 As a matter of fact, it isn't doing anything to the field. 事实上,它在该领域没有做任何事情。 I put gibberish in there and it takes it. 我在里面放了些乱七八糟的东西。

Am I missing something here? 我在这里想念什么吗? Shouldn't it at least format the date or give an error for wrong date format? 它是否应该至少格式化日期或为错误的日期格式提供错误?

Try handling an event on the datagridview, getting the text input and validating whether it's a date or not. 尝试在datagridview上处理事件,获取文本输入并验证是否为日期。 I used the event CellEndEdit , but choose yours as you like. 我使用了事件CellEndEdit ,但是可以根据需要选择您的事件。

在此处输入图片说明

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);
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM