Add DateTimePicker in Datagridview in C#

This article explains how to add a DateTimePicker to Datagridview. So the Datagridview would contain a DateTimePicker column like this:

Add DateTimePicker in Datagridview in C#

First, declare these variables and add this code to Form1():

DateTimePicker dtp = new DateTimePicker();  
Rectangle _Rectangle;  

public Form1()
{
    InitializeComponent();

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

}

Then copy and paste this code:

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            switch (dataGridView1.Columns[e.ColumnIndex].Name)
            {
                case "Column2":

                    _Rectangle = dataGridView1.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)
        {
            dataGridView1.CurrentCell.Value = dtp.Text.ToString();
        }

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

        }


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


More explanation in this video:




Add DateTimePicker in Datagridview in C# Add DateTimePicker in Datagridview in C# Reviewed by Bloggeur DZ on 09:26 Rating: 5

4 commentaires:

  1. А как бы сделать так, чтобы при клике на другую строку не отображались данные, выбранные на предыдущей?

    RépondreSupprimer
  2. This code works ok to put a DateTimePicker on a DataGridView Column, but how do you get the date value chosen and save it to a database?

    RépondreSupprimer

Fourni par Blogger.