开发者

date on DataGridView not formatting as expected

开发者 https://www.devze.com 2023-02-23 09:54 出处:网络
I have a column that uses the DateTime format that was set in the column styles. When a user en开发者_如何转开发ters a date, it\'s not formatting it to the style that it is set to. As a matter of fa

I have a column that uses the DateTime format that was set in the column styles.

When a user en开发者_如何转开发ters 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. I used the event CellEndEdit, but choose yours as you like.

date on DataGridView not formatting as expected

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

精彩评论

暂无评论...
验证码 换一张
取 消