Windows Develop Bookmark and Share   
 index > Windows Forms Designer > DatetimePicker in datagridview
 

DatetimePicker in datagridview

I have a datagridview. I have the data in a DataReader which contains a column only Time. I want to change the column into datetimepicker where the user can edit through datetimepicker.
The code is like this:

MySqlDataReader dr;


MySqlDataReader dr;

MySqlParameter p1 = new MySqlParameter("vDept", cboDept.SelectedValue);
MySqlParameter p2 = new MySqlParameter("vDate", String.Format("{0:yyyy-MM-dd}", dtpAttendanceDate.Value));
MySqlParameter[] sp = new MySqlParameter[] { p1, p2 };

dr = mysql.RunMySQLSPReturnRS(PMS.gcCnnString, "usp_GetAttendanceEntryData", sp);

dsAttendance = mysql.ConvertMySQLDataReaderToDataSet(dr);


Any code for this? how to use this in datagridview.
tkshanty  Thursday, August 20, 2009 6:24 PM
Hello,

In built in DataGridView there is nothing a column exist that provide the functionality as you required but it is possible through custom Template Cell editing.
In ur case the columns contains the time part only. I have been creating the demo application for this purpose it is working fine as you required that i just modify little a bit code that i got from the link .

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
//Test application
namespace TestApplication
{
    //Create a dataGrid View Column
    public class CalendarColumn : DataGridViewColumn
    {
        public CalendarColumn()
            : base(new CalendarCell())
        {
        }
        //Cell template Class
        public override DataGridViewCell CellTemplate
        {
            get
            {
                return base.CellTemplate;
            }
            set
            {
                // Ensure that the cell used for the template is a CalendarCell.
                if (value != null &&
                    !value.GetType().IsAssignableFrom(typeof(CalendarCell)))
                {
                    throw new InvalidCastException("Must be a CalendarCell");
                }
                base.CellTemplate = value;
            }
        }
    }
    //Create custom CalenderCell.
    public class CalendarCell : DataGridViewTextBoxCell
    {

        public CalendarCell()
            : base()
        {
            // Use the short date format.
            this.Style.Format = "hh:mm:ss";
        }

        public override void InitializeEditingControl(int rowIndex, object
            initialFormattedValue, DataGridViewCellStyle dataGridViewCellStyle)
        {
            // Set the value of the editing control to the current cell value.
            base.InitializeEditingControl(rowIndex, initialFormattedValue,
                dataGridViewCellStyle);
            CalendarEditingControl ctl =
                DataGridView.EditingControl as CalendarEditingControl;
            //Shahid
            if (this.Value != null && this.Value.ToString() != "")
                ctl.Value = Convert.ToDateTime(this.Value);
        }

        public override Type EditType
        {
            get
            {
                // Return the type of the editing contol that CalendarCell uses.
                return typeof(CalendarEditingControl);
            }
        }

        public override Type ValueType
        {
            get
            {
                // Return the type of the value that CalendarCell contains.
                return typeof(DateTime);
            }
        }

        public override object DefaultNewRowValue
        {
            get
            {
                // Use the current date and time as the default value.
                return DateTime.Now.ToString("hh:mm:ss");
            }
        }
    }

    class CalendarEditingControl : DateTimePicker, IDataGridViewEditingControl
    {
        DataGridView dataGridView;
        private bool valueChanged = false;
        int rowIndex;

        public CalendarEditingControl()
        {
            this.Format = DateTimePickerFormat.Custom;
            this.CustomFormat = "hh:mm:ss";
            this.ShowUpDown = true;
        }

        // Implements the IDataGridViewEditingControl.EditingControlFormattedValue 
        // property.
        public object EditingControlFormattedValue
        {
            get
            {
                return this.Value.ToString("hh:mm:ss");
            }
            set
            {
                if (value is String)
                {
                    this.Value = DateTime.Parse((String)value);
                }
            }
        }

        // Implements the 
        // IDataGridViewEditingControl.GetEditingControlFormattedValue method.
        public object GetEditingControlFormattedValue(
            DataGridViewDataErrorContexts context)
        {
            return EditingControlFormattedValue;
        }

        // Implements the 
        // IDataGridViewEditingControl.ApplyCellStyleToEditingControl method.
        public void ApplyCellStyleToEditingControl(
            DataGridViewCellStyle dataGridViewCellStyle)
        {
            this.Font = dataGridViewCellStyle.Font;
            this.CalendarForeColor = dataGridViewCellStyle.ForeColor;
            this.CalendarMonthBackground = dataGridViewCellStyle.BackColor;
        }

        // Implements the IDataGridViewEditingControl.EditingControlRowIndex 
        // property.
        public int EditingControlRowIndex
        {
            get
            {
                return rowIndex;
            }
            set
            {
                rowIndex = value;
            }
        }

        // Implements the IDataGridViewEditingControl.EditingControlWantsInputKey 
        // method.
        public bool EditingControlWantsInputKey(
            Keys key, bool dataGridViewWantsInputKey)
        {
            // Let the DateTimePicker handle the keys listed.
            switch (key & Keys.KeyCode)
            {
                case Keys.Left:
                case Keys.Up:
                case Keys.Down:
                case Keys.Right:
                case Keys.Home:
                case Keys.End:
                case Keys.PageDown:
                case Keys.PageUp:
                    return true;
                default:
                    return false;
            }
        }

        // Implements the IDataGridViewEditingControl.PrepareEditingControlForEdit 
        // method.
        public void PrepareEditingControlForEdit(bool selectAll)
        {
            // No preparation needs to be done.
        }

        // Implements the IDataGridViewEditingControl
        // .RepositionEditingControlOnValueChange property.
        public bool RepositionEditingControlOnValueChange
        {
            get
            {
                return false;
            }
        }

        // Implements the IDataGridViewEditingControl
        // .EditingControlDataGridView property.
        public DataGridView EditingControlDataGridView
        {
            get
            {
                return dataGridView;
            }
            set
            {
                dataGridView = value;
            }
        }

        // Implements the IDataGridViewEditingControl
        // .EditingControlValueChanged property.
        public bool EditingControlValueChanged
        {
            get
            {
                return valueChanged;
            }
            set
            {
                valueChanged = value;
            }
        }

        // Implements the IDataGridViewEditingControl
        // .EditingPanelCursor property.
        public Cursor EditingPanelCursor
        {
            get
            {
                return base.Cursor;
            }
        }

        protected override void OnValueChanged(EventArgs eventargs)
        {
            // Notify the DataGridView that the contents of the cell
            // have changed.
            valueChanged = true;
            this.EditingControlDataGridView.NotifyCurrentCellDirty(true);
            base.OnValueChanged(eventargs);
        }
    }
}
Create a new class name CalenderCell , and paste the above code and change the namespace as you r using in ur application.

The Next step is to Add the Clander Column into required DataGridView where you want the functionality. and set the Dataproperty of Calender Column.

And At last Bind the DataGridView to the DataTable , it will show up the result.

Like i am creating a temp DataTable for testing . the code is give below.
//DataTable Temporary
                DataTable Test = new DataTable("Test");
                DataColumn time = new DataColumn("time");
                Test.Columns.Add(time);
                DataRow dr1 = Test.NewRow();
                //1
                dr1["time"] = DateTime.Now.ToString("hh:mm:ss");
                Test.Rows.Add(dr1);
                //2
                dr1 = Test.NewRow();
                dr1["time"] = DateTime.Now.AddMinutes(3).ToString("hh:mm:ss");
                Test.Rows.Add(dr1);
                //3
                dr1 = Test.NewRow();
                dr1["time"] = DateTime.Now.AddMinutes(6).ToString("hh:mm:ss");
                Test.Rows.Add(dr1);
                //4
                dr1 = Test.NewRow();
                dr1["time"] = DateTime.Now.AddMinutes(9).ToString("hh:mm:ss");
                Test.Rows.Add(dr1);
                this.dataGridView1.DataSource = Test.DefaultView;
Good luck any further help let me know about it..



Malik M.Shahid  Saturday, August 22, 2009 11:34 AM
Hello,

In built in DataGridView there is nothing a column exist that provide the functionality as you required but it is possible through custom Template Cell editing.
In ur case the columns contains the time part only. I have been creating the demo application for this purpose it is working fine as you required that i just modify little a bit code that i got from the link .

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
//Test application
namespace TestApplication
{
    //Create a dataGrid View Column
    public class CalendarColumn : DataGridViewColumn
    {
        public CalendarColumn()
            : base(new CalendarCell())
        {
        }
        //Cell template Class
        public override DataGridViewCell CellTemplate
        {
            get
            {
                return base.CellTemplate;
            }
            set
            {
                // Ensure that the cell used for the template is a CalendarCell.
                if (value != null &&
                    !value.GetType().IsAssignableFrom(typeof(CalendarCell)))
                {
                    throw new InvalidCastException("Must be a CalendarCell");
                }
                base.CellTemplate = value;
            }
        }
    }
    //Create custom CalenderCell.
    public class CalendarCell : DataGridViewTextBoxCell
    {

        public CalendarCell()
            : base()
        {
            // Use the short date format.
            this.Style.Format = "hh:mm:ss";
        }

        public override void InitializeEditingControl(int rowIndex, object
            initialFormattedValue, DataGridViewCellStyle dataGridViewCellStyle)
        {
            // Set the value of the editing control to the current cell value.
            base.InitializeEditingControl(rowIndex, initialFormattedValue,
                dataGridViewCellStyle);
            CalendarEditingControl ctl =
                DataGridView.EditingControl as CalendarEditingControl;
            //Shahid
            if (this.Value != null && this.Value.ToString() != "")
                ctl.Value = Convert.ToDateTime(this.Value);
        }

        public override Type EditType
        {
            get
            {
                // Return the type of the editing contol that CalendarCell uses.
                return typeof(CalendarEditingControl);
            }
        }

        public override Type ValueType
        {
            get
            {
                // Return the type of the value that CalendarCell contains.
                return typeof(DateTime);
            }
        }

        public override object DefaultNewRowValue
        {
            get
            {
                // Use the current date and time as the default value.
                return DateTime.Now.ToString("hh:mm:ss");
            }
        }
    }

    class CalendarEditingControl : DateTimePicker, IDataGridViewEditingControl
    {
        DataGridView dataGridView;
        private bool valueChanged = false;
        int rowIndex;

        public CalendarEditingControl()
        {
            this.Format = DateTimePickerFormat.Custom;
            this.CustomFormat = "hh:mm:ss";
            this.ShowUpDown = true;
        }

        // Implements the IDataGridViewEditingControl.EditingControlFormattedValue 
        // property.
        public object EditingControlFormattedValue
        {
            get
            {
                return this.Value.ToString("hh:mm:ss");
            }
            set
            {
                if (value is String)
                {
                    this.Value = DateTime.Parse((String)value);
                }
            }
        }

        // Implements the 
        // IDataGridViewEditingControl.GetEditingControlFormattedValue method.
        public object GetEditingControlFormattedValue(
            DataGridViewDataErrorContexts context)
        {
            return EditingControlFormattedValue;
        }

        // Implements the 
        // IDataGridViewEditingControl.ApplyCellStyleToEditingControl method.
        public void ApplyCellStyleToEditingControl(
            DataGridViewCellStyle dataGridViewCellStyle)
        {
            this.Font = dataGridViewCellStyle.Font;
            this.CalendarForeColor = dataGridViewCellStyle.ForeColor;
            this.CalendarMonthBackground = dataGridViewCellStyle.BackColor;
        }

        // Implements the IDataGridViewEditingControl.EditingControlRowIndex 
        // property.
        public int EditingControlRowIndex
        {
            get
            {
                return rowIndex;
            }
            set
            {
                rowIndex = value;
            }
        }

        // Implements the IDataGridViewEditingControl.EditingControlWantsInputKey 
        // method.
        public bool EditingControlWantsInputKey(
            Keys key, bool dataGridViewWantsInputKey)
        {
            // Let the DateTimePicker handle the keys listed.
            switch (key & Keys.KeyCode)
            {
                case Keys.Left:
                case Keys.Up:
                case Keys.Down:
                case Keys.Right:
                case Keys.Home:
                case Keys.End:
                case Keys.PageDown:
                case Keys.PageUp:
                    return true;
                default:
                    return false;
            }
        }

        // Implements the IDataGridViewEditingControl.PrepareEditingControlForEdit 
        // method.
        public void PrepareEditingControlForEdit(bool selectAll)
        {
            // No preparation needs to be done.
        }

        // Implements the IDataGridViewEditingControl
        // .RepositionEditingControlOnValueChange property.
        public bool RepositionEditingControlOnValueChange
        {
            get
            {
                return false;
            }
        }

        // Implements the IDataGridViewEditingControl
        // .EditingControlDataGridView property.
        public DataGridView EditingControlDataGridView
        {
            get
            {
                return dataGridView;
            }
            set
            {
                dataGridView = value;
            }
        }

        // Implements the IDataGridViewEditingControl
        // .EditingControlValueChanged property.
        public bool EditingControlValueChanged
        {
            get
            {
                return valueChanged;
            }
            set
            {
                valueChanged = value;
            }
        }

        // Implements the IDataGridViewEditingControl
        // .EditingPanelCursor property.
        public Cursor EditingPanelCursor
        {
            get
            {
                return base.Cursor;
            }
        }

        protected override void OnValueChanged(EventArgs eventargs)
        {
            // Notify the DataGridView that the contents of the cell
            // have changed.
            valueChanged = true;
            this.EditingControlDataGridView.NotifyCurrentCellDirty(true);
            base.OnValueChanged(eventargs);
        }
    }
}
Create a new class name CalenderCell , and paste the above code and change the namespace as you r using in ur application.

The Next step is to Add the Clander Column into required DataGridView where you want the functionality. and set the Dataproperty of Calender Column.

And At last Bind the DataGridView to the DataTable , it will show up the result.

Like i am creating a temp DataTable for testing . the code is give below.
//DataTable Temporary
                DataTable Test = new DataTable("Test");
                DataColumn time = new DataColumn("time");
                Test.Columns.Add(time);
                DataRow dr1 = Test.NewRow();
                //1
                dr1["time"] = DateTime.Now.ToString("hh:mm:ss");
                Test.Rows.Add(dr1);
                //2
                dr1 = Test.NewRow();
                dr1["time"] = DateTime.Now.AddMinutes(3).ToString("hh:mm:ss");
                Test.Rows.Add(dr1);
                //3
                dr1 = Test.NewRow();
                dr1["time"] = DateTime.Now.AddMinutes(6).ToString("hh:mm:ss");
                Test.Rows.Add(dr1);
                //4
                dr1 = Test.NewRow();
                dr1["time"] = DateTime.Now.AddMinutes(9).ToString("hh:mm:ss");
                Test.Rows.Add(dr1);
                this.dataGridView1.DataSource = Test.DefaultView;
Good luck any further help let me know about it..



Malik M.Shahid  Saturday, August 22, 2009 11:34 AM

You can use google to search for other answers

Custom Search

More Threads

• Who instantiated this class?
• setting tab Appearance to bottun
• OnDestroyHandle() Question
• How to make a user control contain a windows Form?
• 'HINT TEXT" in c# windows form for disabled controls
• Errors loading the designer - Could not load type 'System.Byte'
• .NET Magic TabControl Help
• Run-time,design-time component
• Missing/worthless DragDrop args in designer
• Where can I find image resource for 'start', 'pause', 'stop' button