views:

429

answers:

2

Hi, I am working on C# winforms application with MS ACCESS as backend. In the datagridview i have a column "startTime". My requirement is I want to validate the startime and if required edit the value programatically and save it. for ex if the user enters "8.00 AM" instead of "8:00 AM" my program should not throw an error saying "invalid datatype"(In the database "StartTime" is a field of type datetime). Rather my program should change 8.00 AM to 8:00 AM and should send 8:00 AM to the backend. pasted below is the code. Any suggestions pls.

private void dgvSession_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
    {
        //** Validation for StartTime
        if (e.ColumnIndex == this.dgvSession.Columns["StartTime"].Index)
        {

        string time = e.FormattedValue.ToString().Trim();
        strtDt = e.FormattedValue.ToString().Trim();
        if (!ValidateTime(time))
        {
            //MessageBox.Show("Entered time is not in a correct format.);

            e.Cancel = true;
            return;
        }
    }
}

public bool ValidateTime(string thetime)
{
    Regex checktime = new Regex(@"(^([0-9]|[0-1][0-9]|[2][0-3])[.:]([0-5][0-9])(\s{0,1})(AM|PM|am|pm|aM|Am|pM|Pm{2,2})$)|(^([0-9]|[1][0-9]|[2][0-3])(\s{0,1})(AM|PM|am|pm|aM|Am|pM|Pm{2,2})$)");

    return checktime.IsMatch(thetime);
}

Thanks in advance Madhu kiran.

+2  A: 

Honestly, my suggestion would be to change the cell to a ComboBox cell with all the times prepopulated. It's always easier to limit what the user CAN enter, rather than allowing them to enter anything, and try to make heads or tails of it later.

Rough code:

        DataGridViewComboBoxColumn timeColumn = new DataGridViewComboBoxColumn();
        timeColumn.DisplayMember = "TimeOfDay";
        DateTime startTime = DateTime.Today;
        for (int i = 0; i <= 23; i++)
        {
            for (int j = 0; j <= 60; j += 15)
            {
                timeColumn.Items.Add(startTime.AddHours(i).AddMinutes(j));
            }
        }

        this.dataGridView1.Columns.Add(timeColumn);

This will do 15 minute increments, you can just change the inner loop if you want it broken down some other way...

BFree
A: 

You would need to determine if the entry is valid and then if it's not create a new function or way to change the entry to a valid datetime. Seeing as users can enter some crazy things that may be hard.

If you do this you can then easily set the value of that cell to the valid entry:

dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = YourNewDateValue;
MDStephens