在datagridview移动一行到当前的datagridview显示数据的第一条和最后一条时怎么让滚动条自动滚动.如移动到当前数据的第一行时.滚动条会自动向上滚动将这一行上面的数据显示出来.移动到当前显示的最后一行时.滚动条自动滚动将最后一行下面的数据显示几条出来.不知道我说的清楚不.那们大牛帮忙解决下.小弟感激不尽.....

解决方案 »

  1.   

    dataGridView1.FirstDisplayedCell = dataGridView1.Rows[index].Cells[0];控制 FirstDisplayedCell 
      

  2.   

    dataGridView1.FirstDisplayedScrollingRowIndex = 99; 也可以。
      

  3.   

    设置下需的属性:this.datagridview.FirstDisplayedScrollingColumnIndex  = datagridview.Columns[X].Index; 横向滚动位置
    this.datagridview.FirstDisplayedScrollingRowIndex = datagridview.Rows[X].Index; 竖向滚动位置
      

  4.   

    代码自己理解一下,注释也很详细了. private void dataGridView1_SelectionChanged(object sender, EventArgs e)
            {
                //Get DisplayBandsInfo field
                var rowBandInfo = typeof(DataGridView).GetField("displayedBandsInfo", BindingFlags.Instance | BindingFlags.NonPublic);
                if (rowBandInfo != null)
                {
                    //Get DisplayBandsInfo value
                    var val = rowBandInfo.GetValue(dataGridView1);
                    //Get first and last displayed row index
                    var firstDisplayedScrollingRow = (int)rowBandInfo.FieldType.GetProperty("FirstDisplayedScrollingRow", BindingFlags.Instance | BindingFlags.Public).GetValue(val, null);
                    var lastDisplayedScrollingRow = firstDisplayedScrollingRow + dataGridView1.DisplayedRowCount(false) - 1;                if (dataGridView1.CurrentCell != null)
                    {
                        //Get current rows index
                        var currentRowIndex = dataGridView1.CurrentCell.RowIndex;
                        //Get scroll method
                        var scrollMethod = typeof(DataGridView).GetMethod("ScrollRowsByCount", BindingFlags.Instance | BindingFlags.NonPublic);
                        if (scrollMethod != null)
                        {
                            //Use negative value scroll up
                            if (currentRowIndex == firstDisplayedScrollingRow)
                            {
                                scrollMethod.Invoke(dataGridView1, new object[] { -2, ScrollEventType.ThumbPosition });
                            }
                            //Use positive value scroll down
                            else if (currentRowIndex == lastDisplayedScrollingRow)
                            {
                                scrollMethod.Invoke(dataGridView1, new object[] { 2, ScrollEventType.ThumbPosition });
                            }
                        }
                    }
                }
            }
      

  5.   

    如果只想滚动一行,修改红色标注的参数
    scrollMethod.Invoke(dataGridView1, new object[] { -1, ScrollEventType.ThumbPosition });
    scrollMethod.Invoke(dataGridView1, new object[] { 1, ScrollEventType.ThumbPosition });