日期:2014-05-18  浏览次数:21164 次

C# winform 中怎么在DataGridView中动态添加DateTimePicker列
怎么在DataGridView中动态添加DateTimePicker列?
谢谢!

------解决方案--------------------
using System;
using System.Collections.Generic;
using System.Text;

using System.Windows.Forms;

namespace Test
{
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;
}
}
}

public class CalendarCell : DataGridViewTextBoxCell
{
public CalendarCell()
: base()
{
// Use the short date format.
this.Style.Format = "d";
}

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
{
ctl.Value = (DateTime)this.Value;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

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

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 con