datagridview中的日历列c#

本文关键字:日历 datagridview | 更新日期: 2023-09-27 18:28:11

基本上,当我编辑Datagridview中的一些列时,我想显示一个日历。

以下操作:在MSDN的Windows窗体中托管控件DataGridView单元格我可以在构建时添加所需的列。

但在我的情况下,我必须使用Excel阅读器提供的数据源,该数据源提供的标题必须连接到日期类型列。

private DataGridView AddCalendars(DataGridView dtgv)
{
  dtgv.DataSource = controller.getEmptyDataTable();     // DataTable provided by excel reader
  var l = dtgv.Columns.Count;
  string[] dateColumns = {"date_received", "date_of_birth"};
  for (var i = 0; i < l; ++i)
  {
    if ( dateColumns.Any( dtgv.Columns[i].HeaderText.Contains )
    {
      dtgv.Columns[i] = new CalendarColumn();      // this line does not work cause by readonly
    }
  }
  return dtgv;
}

如何将日历列控件应用于所选列?

或者,如何通过不同的方式构建Datagridview来获得相同的结果?

datagridview中的日历列c#

围绕这篇文章找到一个可接受的解决方案http://www.codeproject.com/Questions/175124/placing-datetimepicker-in-datagridview

private DateTimePicker cellDateTimePicker;
private List<int> dateColumnsIndexes;
public MainForm()
{
  InitializeComponent();
  /// 
  this.cellDateTimePicker = new DateTimePicker();
  this.cellDateTimePicker.ValueChanged += new EventHandler(cellDateTimePickerValueChanged);
  this.cellDateTimePicker.Visible = false;
  this.cellDateTimePicker.CustomFormat = "dd/MM/yyyy";
  this.cellDateTimePicker.Format = DateTimePickerFormat.Custom;
  this.dataGridView1.Controls.Add(cellDateTimePicker);
  (...)
}
private void dataGridView1_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
{
  var index = masterDataGridView.CurrentCell.ColumnIndex;
  if (this.dateColumnsIndexes.Contains(index))
  {
    Rectangle tempRect = this.dataGridView1.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, false);          
    cellDateTimePicker.Location = tempRect.Location;
    cellDateTimePicker.Width = tempRect.Width;
    try
    {
      cellDateTimePicker.Value = DateTime.Parse(dataGridView1.CurrentCell.Value.ToString());
    }
    catch
    {
      cellDateTimePicker.Value = DateTime.Now;
    }
    cellDateTimePicker.Visible = true;
  }
}
void cellDateTimePickerValueChanged(object sender, EventArgs e)
{
  masterDataGridView.CurrentCell.Value = cellDateTimePicker.Value.ToString("dd/MM/yyyy");
  cellDateTimePicker.Visible = false;
}
private void AddCalendars(DataGridView dtgv)
{
  dateColumnsIndexes = new List<int>();
  dtgv.DataSource = controller.getEmptyDataTable();     // DataTable provided by excel reader
  var l = dtgv.Columns.Count;
  string[] dateColumns = {"date_received", "date_of_birth"};
  for (var i = 0; i < l; ++i)
  {
    if ( dateColumns.Any( dtgv.Columns[i].HeaderText.Contains )
    {
      dateColumnsIndexes.add(i);
    }
 }

}