winforms 将日期时间选择器控件添加到Datagridview中的单行- C# Winform

twh00eeo  于 2023-05-29  发布在  C#
关注(0)|答案(1)|浏览(205)

我有一个DataGridview,在C#窗口窗体中有1个单列和5行。如何将日期时间控件仅添加到第2行和第4行?

// Create a new DateTimePicker control
DateTimePicker dateTimePicker = new DateTimePicker();
dateTimePicker.Format = DateTimePickerFormat.Short;

// Create a DataGridViewComboBoxCell
DataGridViewComboBoxCell comboBoxCell = new DataGridViewComboBoxCell();

// Add the DateTimePicker control to the ComboBox cell
comboBoxCell.Value = dateTimePicker;

// Set the ComboBox cell to the specific row and column
dataGridView1.Rows[1].Cells[1] = comboBoxCell;
dataGridView1.Rows[3].Cells[1] = comboBoxCell;
yvfmudvl

yvfmudvl1#

请看这段代码,它可以完成您正在寻找的任务。单击单元格后,可以根据RowIndex决定是否显示日期时间控件。

using System;
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        private DateTimePicker cellDtp;
        public Form1()
        {
            InitializeComponent();
            for (int i = 0; i < 5; i++)
            {
                DataGridViewCell NewCell = new DataGridViewTextBoxCell();
                NewCell.Value = DateTime.Now.ToString();
                DataGridViewRow NewRow = new DataGridViewRow();
                NewRow.Cells.Add(NewCell);
                dataGridView1.Rows.Add(NewRow);
            }
        }
        
        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            //To check if this is 2nd or 4th Row
            if (e.RowIndex == 1 || e.RowIndex == 3)
            {
                cellDtp = new DateTimePicker();
                dataGridView1.Controls.Add(cellDtp);
                cellDtp.Format = DateTimePickerFormat.Short;
                Rectangle Rectangle = dataGridView1.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true);
                cellDtp.Size = new Size(Rectangle.Width, Rectangle.Height);
                cellDtp.Location = new Point(Rectangle.X, Rectangle.Y);
                cellDtp.Visible = true;
            }
        }
    }
}

As demonstrated here

相关问题