使用dateTimePicker在DataGridView中编辑日期

时间:2010-09-02 18:37:03

标签: c# winforms datagridview datetimepicker

我的winForms DataGridView中有一个DateTime列;目前只能通过手动输入日期“2010/09/02”来编辑该字段,而将DateTimePicker(或等效物)用作编辑器需要什么?

1 个答案:

答案 0 :(得分:0)

DataGridViewDateTimePickerColumn不存在,因此您必须按如下所示手动添加控件。

    <xsl:for-each select="level1/level2/level3/level4">
        <xsl:value-of select="accumulator-before('topid')" />
        <xsl:value-of select="$delimiter" />
        <xsl:value-of select="accumulator-before('subtopid')" />
        <xsl:value-of select="$delimiter" />
        <xsl:value-of select="subid" />
        <xsl:value-of select="$delimiter" />
        <xsl:value-of select="descr" />
        <xsl:value-of select="$newline" />
    </xsl:for-each>

如果需要默认日期,则可以通过“行添加”事件进行处理。

    DateTimePicker dtp = new DateTimePicker();
    Rectangle rectangle;

    public Form1()
    {
        InitializeComponent();

        dgv.Controls.Add(dtp);
        dtp.Visible = false;
        dtp.Format = DateTimePickerFormat.Custom;
        dtp.TextChanged += new EventHandler(dtp_TextChange);
    }

    private void dgv_CellClick(object sender, DataGridViewCellEventArgs e)
    {
        switch (e.ColumnIndex)
        {
            case 5: // Column index of needed dateTimePicker cell

                rectangle = dgv.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;

                break;
        }
    }

    private void dtp_TextChange(object sender, EventArgs e)
    {
        dgv.CurrentCell.Value = dtp.Text.ToString();
    }

    private void dgv_ColumnWidthChanged(object sender, DataGridViewColumnEventArgs e)
    {
        dtp.Visible = false;

    }

    private void dgv_Scroll(object sender, ScrollEventArgs e)
    {
        dtp.Visible = false;
    }