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

时间:2015-04-02 09:14:26

标签: c# datagridview

我试图捕捉用户在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捕获水平滚动的结尾。

2 个答案:

答案 0 :(得分:1)

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

您必须使用ScrollBar.ValueChanged事件,并将ScrollBar.ValueScrollBar.Maximum进行比较,以便做您想做的事。


您可以使用其他解决方案来执行所需操作,而不是在ScrollBar.Scroll上添加事件侦听器:处理DataGridView.Scroll事件并使用DataGridView.FirstDisplayedScrollingRowIndex属性验证datagridview是否向下滚动{ {1}}方法。

这会更简单,更安全。

答案 1 :(得分:0)

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();
    }
}
相关问题