C#--DataGridView添加DateTimePicker時間控件


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Test
{
      
    public partial class Form1: Form
    {
        DateTimePicker  dtp = new DateTimePicker();  //實例化一個DateTimePicker控件
         Rectangle _Rectangle;
        public Form1()
        {
            InitializeComponent();
            dataGridView1.Controls.Add(dtp);  //將時間控件加入DataGridView
            dtp.Visible = false;  //先不顯示
            dtp.Format = DateTimePickerFormat.Custom;  //設置日期格式,2017-11-11
            dtp.TextChanged += new EventHandler(dtp_TextChange); //為時間控件加入事件dtp_TextChange
        }
/*************時間控件選擇時間時****************/
        private void dtp_TextChange(object sender, EventArgs e)
        {
            dataGridView1.CurrentCell.Value = dtp.Text.ToString();  //時間控件選擇時間時,將時間內容賦給所在的單元格
                    }
/****************單元格被單擊,判斷是否是放時間控件的那一列*******************/
        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 0)
            {
                _Rectangle = dataGridView1.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true); //得到所在單元格位置和大小
                dtp.Size = new Size(_Rectangle.Width, _Rectangle.Height); //把單元格大小賦給時間控件
                dtp.Location = new Point(_Rectangle.X, _Rectangle.Y); //把單元格位置賦給時間控件
                dtp.Visible = true;  //顯示控件
            }
            else
                dtp.Visible = false;
        }
/***********當列的寬度變化時,時間控件先隱藏起來,否則單元格寬高變化時時間控件無法跟着變***********/
        private void dataGridView1_ColumnWidthChanged(object sender, DataGridViewColumnEventArgs e)
        {
            dtp.Visible = false;
            
        }
/***********滾動條滾動時,單元格位置發生變化,也隱藏時間控件,否則時間控件位置不動就亂了********/
        private void dataGridView1_Scroll(object sender, ScrollEventArgs e)
        {
            dtp.Visible = false;
        }
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM