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?
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With