Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Editable Date in DataGridView using dateTimePicker

I have a DateTime column in my WinForms DataGridView; currently the field can only be edited by typing the date in manually like "2010/09/02". What would be needed to have a DateTimePicker (or equivalent) used as the editor instead?

like image 491
Dan Is Fiddling By Firelight Avatar asked Sep 02 '10 18:09

Dan Is Fiddling By Firelight


1 Answers

DataGridViewDateTimePickerColumn doesn't exist so you have to add the control manually as below.

DateTimePicker dtp = new DateTimePicker();
Rectangle rectangle;

public Form1()
{
    InitializeComponent();

    dgv.Controls.Add(dtp);
    dtp.Visible = false;
    dtp.Format = DateTimePickerFormat.Custom;
    dtp.TextChanged += new EventHandler(dtp_TextChange);
}

private void dgv_CellClick(object sender, DataGridViewCellEventArgs e)
{
    switch (e.ColumnIndex)
    {
        case 5: // Column index of needed dateTimePicker cell

            rectangle = dgv.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, 
                                                    true);
            dtp.Size = new Size(rectangle.Width, rectangle.Height);
            dtp.Location = new Point(rectangle.X, rectangle.Y);  
            dtp.Visible = true;

            break;
    }
}

private void dtp_TextChange(object sender, EventArgs e)
{
    dgv.CurrentCell.Value = dtp.Text.ToString();
}

private void dgv_ColumnWidthChanged(object sender, DataGridViewColumnEventArgs e)
{
    dtp.Visible = false;
}

private void dgv_Scroll(object sender, ScrollEventArgs e)
{
    dtp.Visible = false;
}

If you need a default date, you can handle it through the RowsAdded event.

private void dgv_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
    dgv.Rows[e.RowIndex].Cells[5].Value = DateTime.Now.ToShortDateString();
}
like image 198
Jozsef Baksa Avatar answered Oct 04 '22 22:10

Jozsef Baksa