C#Datagridview:确保仅由托管控件完成编辑

时间:2018-12-01 16:48:43

标签: c# winforms datagridview datetimepicker

我有一个DataGridView,其中的一个列托管了DateTimePicker控件。当前选择一个日期会将其分配给该单元格的值,但是由于我允许该单元格可编辑以利用CellBeginEdit和CellEndEdit事件,因此您也可以在可能无效的列中键入文本。我该如何做才能仅通过DateTimePicker启用编辑单元格?请参阅下面的部分解决方案:

DateTimePicker dtpVisit;


    private void Form_Load(object sender, EventArgs e)
    {

        dtpVisit = new DateTimePicker();
        dtpVisit.Format = DateTimePickerFormat.Short;
        dtpVisit.Visible = false;
        dtpVisit.Width = 100;
        //DataGridView is called activities
        activities.Controls.Add(dtpVisit);

        dtpVisit.ValueChanged += this.dtpVisit_ValueChanged;
        ...
     }

private void activities_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
    {
        try
        {
            if((activities.Focused) && (activities.CurrentCell.ColumnIndex == 5))
            {
                dtpVisit.Location = activities.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, false).Location;
                dtpVisit.Visible = true;
                dtpVisit.Focus();
                if (activities.CurrentCell.Value != DBNull.Value)
                {
                    dtpVisit.Value = (DateTime)activities.CurrentCell.Value;
                }
                else
                {
                    dtpVisit.Value = DateTime.Today;
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

    }

    private void activities_CellEndEdit(object sender, DataGridViewCellEventArgs e)
    {
        try
        {
            if((activities.Focused) && (activities.CurrentCell.ColumnIndex == 5))
            {
                activities.CurrentCell.Value = dtpVisit.Value.Date;
                dtpVisit.Visible = false;
            }
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

    private void dtpVisit_ValueChanged(object sender, EventArgs e)
    {
        activities.CurrentCell.Value = dtpVisit.Text;
    }

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

0 个答案:

没有答案