小弟最近看到某一元件的sample code,利用DataGridView結合了DateTimePicker
感覺還不錯用,另外我用此方法在增加了NumericUpDown與RadioButton的整合,分享給大家呀..
c#(winfrom)
MainForm.cs(DateTimePicker範例)
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Text;
- using System.Windows.Forms;
- namespace DataGridViewDateTimePicker
- {
- public partial class MainForm : Form
- {
- private bool _CheckChange = false;
- public MainForm()
- {
- InitializeComponent();
- }
- private void MainForm_Load(object sender, EventArgs e)
- {
- // TODO: 這行程式碼會將資料載入 'database1DataSet.Table1' 資料表。您可以視需要進行移動或移除。
- this.table1TableAdapter.Fill(this.database1DataSet.Table1);
- //設定DateTimePicker的高度
- this.dateTimePicker1.Height = this.dataGridView1.Height;
- }
- //將DateTimePicker控制項定位在DataGridView的Column上
- private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e)
- {
- if (this.dataGridView1.Columns[e.ColumnIndex].HeaderText == "date")
- {
- Rectangle r = this.dataGridView1.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, false);
- r = this.dataGridView1.RectangleToScreen(r);
- this.dateTimePicker1.Location = this.RectangleToClient(r).Location;
- this.dateTimePicker1.Size = r.Size;
- this._CheckChange = true;
- this.dateTimePicker1.Text = this.dataGridView1.CurrentCell.Value.ToString();
- this._CheckChange = false;
- this.dateTimePicker1.Visible = true;
- }
- else
- {
- this.dateTimePicker1.Visible = false;
- }
- }
- //改變Column的值
- private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
- {
- if (_CheckChange) return;
- this.dataGridView1.CurrentCell.Value = this.dateTimePicker1.Text;
- }
- }
- }
執行結果:
DateTimePicker
NumericUpDown
RadioButton