Sunday, March 1, 2009

DateTimePicker in datagridview using C#

If you want to add datetimepicker in datagridview then you have to create a custom control and its very easy.

If you create a seperate project and then you can use the dll in you future projects.

I have given the code just copy and past your project. Make it as seperate project then simply by adding the dll you can do it.

Step 1: Create a project name: datetimePicker_gridview

Step 2: Create the CalendarCell class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace datetimePicker_gridview
{
class CalendarCell : DataGridViewTextBoxCell
{

public CalendarCell(): base()
{
// Use the short date format.
this.Style.Format = "dd MMM yy";
}

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;
try
{
if (this.Value != DBNull.Value)
ctl.Value = (DateTime)this.Value;
}
catch (Exception err) { }
}

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;
}
}

}
}


Step 3: Create the CalendarColumn class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System;
using System.Windows.Forms;

namespace datetimePicker_gridview
{
public class CalendarColumn : DataGridViewColumn
{
public CalendarColumn(): base(new CalendarCell())
{
}

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;
}
}

}
}


Step 4: Create the CalendarEditingControl class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

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

public CalendarEditingControl()
{
this.Format = DateTimePickerFormat.Short;
}

// Implements the IDataGridViewEditingControl.EditingControlFormattedValue
// property.
public object EditingControlFormattedValue
{
get
{
return this.Value.ToShortDateString();
}
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 !dataGridViewWantsInputKey;
}
}

// 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);
}

}
}


Now Just create a form and test it.

private DataGridView dataGridView1 = new DataGridView();

public Form1()
{
InitializeComponent();

this.Controls.Add(this.dataGridView1);
this.Load += new EventHandler(Form1_Load);
this.Text = "DataGridView calendar column ";
}

private void Form1_Load(object sender, EventArgs e)
{
CalendarColumn col = new CalendarColumn();
col.HeaderText = "Date";
this.dataGridView1 .Columns.Add(col);
this.dataGridView1 .RowCount = 5;
foreach (DataGridViewRow row in this.dataGridView1 .Rows)
{
row.Cells[0].Value = DateTime.Now;
}
}


Thats all. Now use it.


One more thing you can do. when you are create the datagridview after createing and binding with dataSet

1. Click on CodeView in your form (which containig datagridview)
2. got to InitializeComponent();
3. Change your desire column type from System.Windows.Forms.DataGridViewTextBoxColumn to datetimePicker_gridview.CalendarColumn

No check it.

Thanks

7 comments:

  1. hello Mr. Anowar this code is very helpful
    -------------------------
    but with a problem that this code Add three column with datetimepicker


    but thanx
    addy.....

    ReplyDelete
  2. this code is very useful for my project thanx buddy..

    ReplyDelete
  3. Thank You so much ,

    It really helps

    ReplyDelete
  4. Help me...

    I got some error......

    I need datagridview column which contain only time like(hh:mm tt)....

    Actually i get this by change the datetimepicker format property in your code.....

    but i get error when i set datapropertyname for that column...

    ReplyDelete
  5. Hi Mr. Anowar ! Thanks very much for your code. It'is very helpful.

    ReplyDelete
  6. how to show date format in dd mm yyyy
    please it's urgent

    ReplyDelete
  7. http://www.freelearningdz.info/2016/02/add-datetimepicker-in-datagridview.html

    ReplyDelete