2017年8月2日 星期三

C# x dateTimePicker x datagridview x 儲存格結合


C# x dateTimePicker x datagridview x 儲存格結合

比原出處多了點東西 : 標題列不可以點、不會改掉其他儲存格

Form裡面要有 :

DataGridView * 1

/////////////////////以下 程式碼/////////////////////
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;

namespace WindowsFormsApplication33
{
    public partial class Form1 : Form
    {
        DateTimePicker oDateTimePicker = new DateTimePicker();

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            List<MyData> oMyDataList = new List<MyData>();

            MyData obj1 = new MyData(1, DateTime.Now, "John");
            MyData obj2 = new MyData(2, DateTime.Now, "Sam");
            MyData obj3 = new MyData(3, DateTime.Now, "Ray");

            oMyDataList.Add(obj1);
            oMyDataList.Add(obj2);
            oMyDataList.Add(obj3);

            dataGridView1.DataSource = oMyDataList;
        }

        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 1 && e.RowIndex>=0)
            {
                dataGridView1.Controls.Add(oDateTimePicker);
                oDateTimePicker.Format = DateTimePickerFormat.Short;
                Rectangle oRectangle = dataGridView1.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true);
                oDateTimePicker.Size = new Size(oRectangle.Width, oRectangle.Height);
                oDateTimePicker.Location = new Point(oRectangle.X, oRectangle.Y);
                oDateTimePicker.CloseUp += new EventHandler(oDateTimePicker_CloseUp);
                oDateTimePicker.TextChanged += new EventHandler(dateTimePicker_OnTextChange);
                oDateTimePicker.Visible = true;
            }
            else
            {
                oDateTimePicker.Visible = false;
            }
        }
        public void dateTimePicker_OnTextChange(object sender, EventArgs e)
        {
            dataGridView1.CurrentCell.Value = oDateTimePicker.Text.ToString();
        }
        public void oDateTimePicker_CloseUp(object sender, EventArgs e)
        {
            oDateTimePicker.Visible = false;
        }
    }
    class MyData
    {
        public int ID { get; set; }
        public DateTime Date { get; set; }
        public string Name { get; set; }
        public MyData(int id, DateTime dt, string name)
        {
            ID = id;
            Date = dt;
            Name = name;
        }
    }
}

/////////////////////以上 程式碼/////////////////////



執行畫面





























參考資料 : http://www.c-sharpcorner.com/UploadFile/0f68f2/embedding-calendar-datetimepicker-control-into-datagridvie586/

沒有留言:

張貼留言