You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# WinForm:如何为DataGridView指定行添加DateTimePicker控件

在C# Windows窗体中为DataGridView指定行添加DateTimePicker控件

你提供的代码存在问题——不能用DataGridViewComboBoxCell来存放DateTimePicker控件,这两者无法正确绑定。正确的做法是直接使用DataGridViewDateTimePickerCell替换目标行的单元格,具体实现如下:

实现步骤与代码

  1. 确保你的DataGridView已完成基础初始化(比如通过设计器或代码创建1列5行)
  2. 为目标行分别创建DataGridViewDateTimePickerCell实例,设置日期显示格式
  3. 将这些单元格替换到DataGridView的对应位置
// 如果未通过设计器设置DataGridView的行列,可通过代码初始化
dataGridView1.ColumnCount = 1;
dataGridView1.RowCount = 5;

// 为第2行(索引1)添加DateTimePicker单元格
DataGridViewDateTimePickerCell dateCellRow2 = new DataGridViewDateTimePickerCell();
dateCellRow2.Format = DateTimePickerFormat.Short;
dataGridView1.Rows[1].Cells[0] = dateCellRow2; // 仅1列,列索引为0

// 为第4行(索引3)添加DateTimePicker单元格
DataGridViewDateTimePickerCell dateCellRow4 = new DataGridViewDateTimePickerCell();
dateCellRow4.Format = DateTimePickerFormat.Short;
dataGridView1.Rows[3].Cells[0] = dateCellRow4;

关键说明

  • DataGridView的行、列索引均从0开始,因此第2行对应索引1,第4行对应索引3;由于只有1列,列索引固定为0。
  • 必须为每个目标行单独创建DataGridViewDateTimePickerCell实例,不能复用同一个单元格对象,否则会引发控件显示或交互异常。

内容的提问来源于stack exchange,提问作者Alberto

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 22:32:40