繁体   English   中英

使用键盘滚动时,datagridview Scroll事件不会触发

[英]datagridview Scroll event not firing when scrolling using keyboard

我试图捕捉用户在 datagridview 中结束水平滚动的时刻。 我需要这个来重新定位网格标题中的按钮。

到目前为止,我所做的是添加一个我在此链接上找到的 scrollListener: How can I receive the "scroll box" type scroll events from a DataGridView?

这非常有效,除非使用键盘滚动不会触发滚动事件。 当我在我的代码中将鼠标悬停在 Scroll 事件上时,它会指出“当滚动框被鼠标或键盘操作移动时发生”。 因此,在使用键盘滚动时应该触发该事件,但事实并非如此。

我的代码是这样的:

    bool addScrollListener(DataGridView dgv)
    {
        // capture horizonal scrolling and redirect to s_Scroll. Purpose is to redraw buttons after scrolling
        bool Result = false;

        Type t = dgv.GetType();
        PropertyInfo pi = t.GetProperty("HorizontalScrollBar", BindingFlags.Instance | BindingFlags.NonPublic);
        ScrollBar s = null;

        if (pi != null)
            s = pi.GetValue(dgv, null) as ScrollBar;

        if (s != null)
        {
            s.Scroll += new ScrollEventHandler(s_Scroll);

            Result = true;
        }

        return Result;
    }

    void s_Scroll(object sender, ScrollEventArgs e)
    {
        // if grid is done scrolling horizontal, than redraw our buttons
        if (e.Type == ScrollEventType.EndScroll)
        {
            // code works well, but only get here when scrolling with mouse
            PositionButtons();
        }
    }

所以我的问题是,当用户使用鼠标滚动时,s_Scroll 事件被触发,但是当使用键盘滚动时,s_Scroll 事件根本不会被触发。

我的问题是如何解决这个问题,以便在两种情况下都触发事件,如果不可能,还有另一种方法可以从 datagridview 中捕获水平滚动的结尾。

DataGridView ,键盘操作由DataGridView处理以更新当前单元格位置。

您必须使用ScrollBar.ValueChanged事件并将ScrollBar.ValueScrollBar.Maximum进行比较才能执行您想要的操作。


您有另一种解决方案来执行您想要的操作,而不是在ScrollBar.Scroll上添加事件侦听器:处理DataGridView.Scroll事件并使用DataGridView.FirstDisplayedScrollingRowIndex属性和DataGridView.DisplayedRowCount(true)方法验证 datagridview 是否向下滚动。

那会更简单,更安全。

private void TransactionsDGV_KeyUp(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.End)
    {
        e.Handled = true;
        DataGridViewCell cell = TransactionsDGV.Rows[TransactionsDGV.Rows.Count-2].Cells[0];
        TransactionsDGV.CurrentCell = cell;
        TransactionsDGV.BeginEdit(true);
        TransactionsDGV.EndEdit();
    }

    if (e.KeyCode == Keys.Home)
    {
        e.Handled = true;
        DataGridViewCell cell = TransactionsDGV.Rows[0].Cells[0];
        TransactionsDGV.CurrentCell = cell;
        TransactionsDGV.BeginEdit(true);
        TransactionsDGV.EndEdit();
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM