0

我的 DataGridView 中有一个DateTimePicker单元格。我希望能够在单击按钮时进入编辑模式并删除日历。我能够毫无困难地完成第一部分,但第二部分不起作用。如果我有一个独立的 DateTimePicker,则 SendKeys 调用会按预期工作。

//Select the cell and enter edit mode -  works
myDGV.CurrentCell = myDGV[calColumn.Index, e.RowIndex];
myDGV.BeginEdit(true);

//Send an ALt-Down keystroke to drop the calendar  - doesn't work
SendKeys.SendWait("%{DOWN}");

从调试来看,我认为问题在于击键被发送到 DGV,而不是我试图编辑的特定单元格。我认为的原因是我已经将代码用于记录网格 KeyPress 和 KeyDown 事件接收到的键。他们记录了我在网格周围的箭头和 SendKeys 发送的键,但不是我通过输入编辑单元格时的那些。

4

2 回答 2

1

请参阅我对C# Winforms DataGridView Time Column的回答。我相信它会完美地满足您的需求。您也可以将它用于具有 ComboBox 的列。

于 2010-09-02T23:51:51.217 回答
0

我最近重新审视了这个问题,因为 0A0D 提供的实现并不总是能很好地与网格的键盘导航(箭头/选项卡)配合使用。有时可以绕过DateTimePicker并将文本输入到DataGridViewTextBoxCell. 这导致我的验证逻辑崩溃了;在未能找到防止滑倒发生的方法后,我决定尝试让自定义列再次工作。

修复结果非常简单。我创建了一个扩展DateTimePicker的方法来发送显示日历所需的击键。

/// <summary>
/// Extended DateTimePicker with a method to programmatically display the calendar.
/// </summary>
class DateTimePickerEx : DateTimePicker
{
    [DllImport("user32.dll")]
    private static extern bool PostMessage(
    IntPtr hWnd, // handle to destination window
    Int32 msg, // message
    Int32 wParam, // first message parameter
    Int32 lParam // second message parameter
    );

    const Int32 WM_LBUTTONDOWN = 0x0201;

    /// <summary>
    /// Displays the calendar input control.
    /// </summary>
    public void ShowCalendar()
    {
        Int32 x = Width - 10;
        Int32 y = Height / 2;
        Int32 lParam = x + y * 0x00010000;

        PostMessage(Handle, WM_LBUTTONDOWN, 1, lParam);
    }
}

然后我将MSDN DateTime 列示例修改为CalendarEditingControl继承自DateTimePickerEx.

然后在托管的表单中,DataGridView我使用该EditingControl属性来调用该ShowCalendar()方法。

DateTimePickerEx dtp = myDataGridView.EditingControl as DateTimePickerEx;
if (dtp != null)
    dtp.ShowCalendar();
于 2012-11-02T19:48:05.157 回答