Csharp DataGridView自定义添加DateTimePicker控件日期列

/// <summary>
 /// DataGridView自定义添加DateTimePicker控件日期列 参考http://msdn.microsoft.com/en-us/library/7tas5c80.aspx
 /// 涂聚文 缔友计算机信息技术有限公司
 /// 2011-11-16 捷为工作室
 /// </summary>
 public class GeovinDuCalendarColumn : DataGridViewColumn
 {
     /// <summary>
     /// 
     /// </summary>
     public GeovinDuCalendarColumn()
         : base(new CalendarCell())
     {
     }
     /// <summary>
     /// 
     /// </summary>
     public override DataGridViewCell CellTemplate
     {
         get
         {
             return base.CellTemplate;
         }
         set
         {
          
             if (value != null &&
                 !value.GetType().IsAssignableFrom(typeof(CalendarCell)))
             {
                 throw new InvalidCastException("Must be a CalendarCell");
             }
             base.CellTemplate = value;
         }
     }
 }
 /// <summary>
 /// DataGridView 添加日期列
 /// 涂聚文 缔友计算机信息技术有限公司
 /// 2011-11-16 捷为工作室
 /// </summary>
 public class CalendarCell : DataGridViewTextBoxCell
 {

     public CalendarCell()
         : base()
     {
     
         this.Style.Format = "d";
     }

     public override void InitializeEditingControl(int rowIndex, object
         initialFormattedValue, DataGridViewCellStyle dataGridViewCellStyle)
     {

         base.InitializeEditingControl(rowIndex, initialFormattedValue,
             dataGridViewCellStyle);
         CalendarEditingControl ctl =
             DataGridView.EditingControl as CalendarEditingControl;
   
         if (this.Value == null)
         {
             ctl.Value = (DateTime)this.DefaultNewRowValue;
         }
         else
         {
             ctl.Value = (DateTime)this.Value;
         }
     }

     public override Type EditType
     {
         get
         {
           
             return typeof(CalendarEditingControl);
         }
     }

     public override Type ValueType
     {
         get
         {
           

             return typeof(DateTime);
         }
     }

     public override object DefaultNewRowValue
     {
         get
         {
         
             return DateTime.Now;
         }
     }
 }
 /// <summary>
 ///DataGridView 添加日期列
 /// 涂聚文 缔友计算机信息技术有限公司
 /// 2011-11-16 捷为工作室
 /// </summary>
 class CalendarEditingControl : DateTimePicker, IDataGridViewEditingControl
 {
     DataGridView dataGridView;
     private bool valueChanged = false;
     int rowIndex;

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


     public object EditingControlFormattedValue
     {
         get
         {
             return this.Value.ToShortDateString();
         }
         set
         {
             if (value is String)
             {
                 try
                 {

                     this.Value = DateTime.Parse((String)value);
                 }
                 catch
                 {
           
                     this.Value = DateTime.Now;
                 }
             }
         }
     }


     public object GetEditingControlFormattedValue(
         DataGridViewDataErrorContexts context)
     {
         return EditingControlFormattedValue;
     }


     public void ApplyCellStyleToEditingControl(
         DataGridViewCellStyle dataGridViewCellStyle)
     {
         this.Font = dataGridViewCellStyle.Font;
         this.CalendarForeColor = dataGridViewCellStyle.ForeColor;
         this.CalendarMonthBackground = dataGridViewCellStyle.BackColor;
     }


     public int EditingControlRowIndex
     {
         get
         {
             return rowIndex;
         }
         set
         {
             rowIndex = value;
         }
     }


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


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


     public bool RepositionEditingControlOnValueChange
     {
         get
         {
             return false;
         }
     }


     public DataGridView EditingControlDataGridView
     {
         get
         {
             return dataGridView;
         }
         set
         {
             dataGridView = value;
         }
     }


     public bool EditingControlValueChanged
     {
         get
         {
             return valueChanged;
         }
         set
         {
             valueChanged = value;
         }
     }


     public Cursor EditingPanelCursor
     {
         get
         {
             return base.Cursor;
         }
     }

     protected override void OnValueChanged(EventArgs eventargs)
     {

         valueChanged = true;
         this.EditingControlDataGridView.NotifyCurrentCellDirty(true);
         base.OnValueChanged(eventargs);
     }
 }

调用:

           //dataGridView1.Columns[3].HeaderText = "入職日期";
           GeovinDuCalendarColumn col = new GeovinDuCalendarColumn();
           this.dataGridView1.Columns.Insert(3,col);
           col.HeaderText = "入職日期";

/// <summary>
       /// 设置默认值
       /// </summary>
       /// <param name="sender"></param>
       /// <param name="e"></param>
       private void dataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
       {
           if (dataGridView1.Rows.Count >= 1) //设定默认日期
           {
               this.dataGridView1.Rows[e.RowIndex].Cells[2].Value = "20E8C162-C09C-4F7A-9C97-0CA50E201F6B";
               this.dataGridView1.Rows[e.RowIndex].Cells[3].Value = DateTime.Now;
               this.dataGridView1.Rows[e.RowIndex].Cells[4].Value = "C50E08D5-7529-4F86-966E-9497AD67EA0C";
           }
       }



您可以尝试在 `DateTimePicker` 的 `DropDown` 事件中自定义下拉控件。在自定义的下拉控件添加一个 `DataGridView` 控件,并设置其 `DataSource` 属性为一个包含日期和对应周数的数据源。 以下是代码示例: ```csharp private void dateTimePicker1_DropDown(object sender, EventArgs e) { // 创建一个自定义控件,用于替换 DateTimePicker 的默认下拉控件 CustomDropDown dropDown = new CustomDropDown(); // 创建一个 DataGridView 控件,用于显示日期和对应周数 DataGridView dgv = new DataGridView(); dgv.Dock = DockStyle.Fill; dgv.AutoGenerateColumns = false; // 添加日期 DataGridViewTextBoxColumn dateColumn = new DataGridViewTextBoxColumn(); dateColumn.DataPropertyName = "Date"; dateColumn.HeaderText = "日期"; dgv.Columns.Add(dateColumn); // 添加周数 DataGridViewTextBoxColumn weekColumn = new DataGridViewTextBoxColumn(); weekColumn.DataPropertyName = "Week"; weekColumn.HeaderText = "周数"; dgv.Columns.Add(weekColumn); // 绑定数据源 dgv.DataSource = GetDataSource(); // 将 DataGridView 添加自定义控件中 dropDown.Controls.Add(dgv); // 将自定义控件显示在 DateTimePicker 下方 dropDown.Show(dateTimePicker1, new Point(0, dateTimePicker1.Height)); } // 返回包含日期和对应周数的数据源 private DataTable GetDataSource() { DataTable dt = new DataTable(); dt.Columns.Add("Date", typeof(DateTime)); dt.Columns.Add("Week", typeof(int)); // 假设需要显示当前月份的日期和对应周数 DateTime currentDate = DateTime.Now; int currentMonth = currentDate.Month; int currentYear = currentDate.Year; DateTime startDate = new DateTime(currentYear, currentMonth, 1); DateTime endDate = startDate.AddMonths(1).AddDays(-1); // 计算每一天的周数,并添加到数据源中 for (DateTime date = startDate; date <= endDate; date = date.AddDays(1)) { int week = GetWeekOfYear(date); dt.Rows.Add(date, week); } return dt; } // 计算指定日期的周数 private int GetWeekOfYear(DateTime date) { CultureInfo ci = CultureInfo.CurrentCulture; CalendarWeekRule cwr = ci.DateTimeFormat.CalendarWeekRule; DayOfWeek dow = ci.DateTimeFormat.FirstDayOfWeek; return ci.Calendar.GetWeekOfYear(date, cwr, dow); } // 自定义下拉控件 private class CustomDropDown : ToolStripDropDown { public CustomDropDown() { // 设置下拉控件的样式 this.AutoSize = false; this.DoubleBuffered = true; this.ResizeRedraw = true; this.Padding = new Padding(0); } protected override void OnPaint(PaintEventArgs e) { // 绘制下拉控件的背景 e.Graphics.Clear(this.BackColor); base.OnPaint(e); } } ``` 请注意,以上代码仅提供了一种实现思路,您可以根据具体需求进行修改和优化。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值