C# Winform DataGridView在列中使用DateTimePicker控件

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C# Winform DataGridView在列中使用DateTimePicker控件相关的知识,希望对你有一定的参考价值。

怎么使用,我要在列中输入日期

赞同二楼,贴出代码供你参考

代码如下:
using System;
using System.Windows.Forms;
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


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



调用,测试:
DataGridView dataGridView1 = new DataGridView();
CalendarColumn col = new CalendarColumn();
this.dataGridView1.Columns.Add(col);

this.dataGridView1.RowCount = 5;
foreach (DataGridViewRow row in this.dataGridView1.Rows)

row.Cells[0].Value = DateTime.Now;
参考技术A 可以编写自定义的DataGridViewColumn和DataGridViewCell控件提供自己的编辑承载控件,具体的代码你可以参考msdn,到google搜索 如何:在 Windows 窗体 DataGridView 单元格中承载控件 ,他的例子就是提供一个承载DateTimePicker的

C# Winform DataGridView 控件的基本使用

▲ 运行截图


两个注意点

  1. 报错:DataGridView 控件中至少有一列没有单元格模板

解决方法

一个小误区,你看看设计窗体生成的代码,DataGridView 的列不是 GridViewColumn 而是 DataGridViewTextBoxColumn
你只要添加这个类型的对象就可以了,我也是饶了好久才绕出来

  1. Paint事件,重绘了dataGridView外边框颜色。

代码

using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CsTest
{
    public partial class FormMain : Form
    {
        public FormMain()
        {
            InitializeComponent();

            _students.Add(new Student() { Name = "张三", Age = 10, Gender = "男", Chinese = 50, English = 100, Math = 99 });
            _students.Add(new Student() { Name = "李四", Age = 11, Gender = "女", Chinese = 23, English = 78, Math = 80 });
            _students.Add(new Student() { Name = "王五", Age = 15, Gender = "女", Chinese = 23, English = 78, Math = 80 });

            DataGridViewSetting();
        }

        private List<Student> _students = new List<Student>();

        private void DataGridViewSetting()
        {
            DataGridViewSetting(dgv_Test);
        }

        private void DataGridViewSetting(DataGridView dataGridView)
        {
            dataGridView.AllowUserToAddRows = false;
            dataGridView.AllowUserToDeleteRows = false;
            dataGridView.ReadOnly = true;
            dataGridView.RowHeadersVisible = false; // 控制行头的显示
            dataGridView.BackgroundColor = SystemColors.ButtonFace;
            dataGridView.ColumnHeadersHeight = 25;
            dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;

            //下面这种会抛异常(没有单元格模板), 不能添加 DataGridViewColumn 对象,而是 DataGridViewTextBoxColumn 对象
            //dataGridView.Columns.Add(new DataGridViewColumn() { Name = "Name", HeaderText = "姓名", DataPropertyName = "Name", CellTemplate = new DataGridViewTextBoxCell() });
            //dataGridView.Columns.Add(new DataGridViewColumn() { Name = "Age", HeaderText = "年龄", DataPropertyName = "Age", CellTemplate = new DataGridViewTextBoxCell() });
            //dataGridView.Columns.Add(new DataGridViewColumn() { Name = "Gender", HeaderText = "性别", DataPropertyName = "Gender", CellTemplate = new DataGridViewTextBoxCell() });
            //dataGridView.Columns.Add(new DataGridViewColumn() { Name = "Chinese", HeaderText = "语文", DataPropertyName = "Chinese", CellTemplate = new DataGridViewTextBoxCell() });
            //dataGridView.Columns.Add(new DataGridViewColumn() { Name = "Math", HeaderText = "数学", DataPropertyName = "Math", CellTemplate = new DataGridViewTextBoxCell() });
            //dataGridView.Columns.Add(new DataGridViewColumn() { Name = "English", HeaderText = "英语", DataPropertyName = "English", CellTemplate = new DataGridViewTextBoxCell() });

            dataGridView.Columns.Add(new DataGridViewTextBoxColumn() { Name = "Name", HeaderText = "姓名", DataPropertyName = "Name" });
            dataGridView.Columns.Add(new DataGridViewTextBoxColumn() { Name = "Age", HeaderText = "年龄", DataPropertyName = "Age" });
            dataGridView.Columns.Add(new DataGridViewTextBoxColumn() { Name = "Gender", HeaderText = "性别", DataPropertyName = "Gender" });
            dataGridView.Columns.Add(new DataGridViewTextBoxColumn() { Name = "Chinese", HeaderText = "语文", DataPropertyName = "Chinese" });
            dataGridView.Columns.Add(new DataGridViewTextBoxColumn() { Name = "Math", HeaderText = "数学", DataPropertyName = "Math" });
            dataGridView.Columns.Add(new DataGridViewTextBoxColumn() { Name = "English", HeaderText = "英语", DataPropertyName = "English" });

            // 下面这种方式也可以,不过要多写一行代码

            //dataGridView.Columns.Add("Name", "姓名");
            //dataGridView.Columns["Name"].DataPropertyName = "Name";
            //dataGridView.Columns.Add("Age", "年龄");
            //dataGridView.Columns["Age"].DataPropertyName = "Age";
            //dataGridView.Columns.Add("Gender", "性别");
            //dataGridView.Columns["Gender"].DataPropertyName = "Gender";
            //dataGridView.Columns.Add("Chinese", "语文");
            //dataGridView.Columns["Chinese"].DataPropertyName = "Chinese";
            //dataGridView.Columns.Add("Math", "数学");
            //dataGridView.Columns["Math"].DataPropertyName = "Math";
            //dataGridView.Columns.Add("English", "英语");
            //dataGridView.Columns["English"].DataPropertyName = "English";

            dataGridView.DataSource = _students;
            dataGridView.Paint += dgv_Test_Paint;  // 重绘制dataGridView外边框颜色
        }

        // 重绘制dataGridView外边框颜色
        private void dgv_Test_Paint(object sender, PaintEventArgs e)
        {
            e.Graphics.DrawRectangle(Pens.Red, new Rectangle(0, 0, this.dgv_Test.Width - 1, this.dgv_Test.Height - 1));
        }
    }

    public class Student
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public string Gender { get; set; }
        public int Chinese { get; set; }
        public int Math { get; set; }
        public int English { get; set; }
    }
}

以上是关于C# Winform DataGridView在列中使用DateTimePicker控件的主要内容,如果未能解决你的问题,请参考以下文章

C# winform datagridview如何计算统计

C# winform dataGridView批量数据修改

c# winform datagridview界面上的行删了,但datagridview数据源没有同步如何解决

c# winform datagridview怎么能达到如图的效果

winform c# Datagridview 选中行 急!!!

C# winform 如何用datagridview增、删、改数据