shmandor
shmandor

Reputation: 891

How to host datetimepicker in DataGridView control in C# winforms

private void showdate(DataGridViewCellEventArgs e)
{
    dateTimePicker1.Size = vacation_transDataGridView.CurrentCell.Size;
    dateTimePicker1.Top = vacation_transDataGridView.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true).Top + vacation_transDataGridView.Top;
    dateTimePicker1.Left = vacation_transDataGridView.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true).Left + vacation_transDataGridView.Left;

    if (!(object.Equals(Convert.ToString(vacation_transDataGridView.CurrentCell.Value),"")))
    {
        dateTimePicker1.Value = Convert.ToDateTime(vacation_transDataGridView.CurrentCell.Value);
        //dateTimePicker1.Visible = false;
    }

    dateTimePicker1.Visible = true;
}

This code in dgv cell_click event

Upvotes: 0

Views: 4737

Answers (3)

Rizwan Ahmed
Rizwan Ahmed

Reputation: 473

private void dgtest_CellClick(object sender, DataGridViewCellEventArgs e)
{
    if (e.ColumnIndex == 0)
    {
         dtp = new DateTimePicker();
        dgtest.Controls.Add(dtp);
        dtp.Format = DateTimePickerFormat.Short;
        Rectangle Rectangle = dgtest.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true);
        dtp.Size = new Size(Rectangle.Width, Rectangle.Height);
        dtp.Location = new Point(Rectangle.X, Rectangle.Y);
        dtp.CloseUp += new EventHandler(dtp_CloseUp);
        dtp.TextChanged += new EventHandler(dtp_OnTextChange);
        dtp.Visible = true;
    }
}

private void dtp_OnTextChange(object sender, EventArgs e)
{

    dgtest.CurrentCell.Value = dtp.Text.ToString();
}

void dtp_CloseUp(object sender, EventArgs e)
{ 
    dtp.Visible = false;
}

Upvotes: 0

Chris McKenzie
Chris McKenzie

Reputation: 3841

There is an example of exactly this thing on MSDN. http://msdn.microsoft.com/en-us/library/7tas5c80.aspx

Upvotes: 1

Oliver
Oliver

Reputation: 45071

Unfortunately there isn't such a Cell or Column Type you can use (as far as i know). But Microsoft provides an example on how to get a NumericUpDown (that also doesn't exist) into a DataGridView.

Maybe you can adopt this example to get your DateTimePicker into a DataGridView.

Upvotes: 0

Related Questions