滚动到C#DataGridView的底部

Mot*_*mbo 34 c# datagridview scrollbar winforms

我正在尝试在C#WinForm中滚动到DataGridView的底部.

此代码适用于TextBox:

textbox_txt.SelectionStart = textbox_txt.Text.Length;
textbox_txt.ScrollToCaret();
Run Code Online (Sandbox Code Playgroud)

...但我不知道如何使用DataGridView.有什么帮助吗?

Mar*_*all 77

要滚动到底部DataGridView试试这个.

dataGridView1.FirstDisplayedScrollingRowIndex = dataGridView1.RowCount-1;
Run Code Online (Sandbox Code Playgroud)

  • 有用,谢谢.如果您的DataGridView有隐藏的行,那么您需要检查行可见性,因为DataGridView不允许您滚动到不可见的行. (2认同)
  • 如果存在当前选定的单元格,则此方法无效,因为DataGridView会尝试保持该单元格可见.有没有办法强制滚动?我不想更改当前单元格,只是让它滚动屏幕. (2认同)

小智 5

作为一名商业程序员,我使用 C# DLL 来处理我所有的 DataGridView 项目,这让我可以在任何项目中自由使用语言。我所有的程序都会捕获所有按键,以便我可以将它们用于我自己的目的。对于 DataGridView 滚动,我将 PageUp/PageDown 键用于单页,Ctrl/Page 用于单行,Alt/Page 用于顶部 (Up) 和底部 (Down)。C#代码和Basic调用顺序如下:

//---------- C# Dll Partial Source -----------

public int RowShow
   { get { return vu.DisplayedRowCount(false); } }

public int RowCount 
   { get { return vu.RowCount; } }

public void PageMove(int rows)
{
    int rowlimit = vu.RowCount - 1;
    int calc = vu.FirstDisplayedScrollingRowIndex + rows;

    if (calc > rowlimit) calc = rowlimit;  // Go to bottom
    if (calc < 0)        calc = 0;         // Go to top

    vu.FirstDisplayedScrollingRowIndex = calc;
}

// ---------- End Data Grid View ----------



//---------- Calling Program C# ----------

public void Page_Key(int val, int lastKey)
{
    int inc = 1;                // vu is DataGridView

    If (val == 33) inc = -1;

    int rowsDisp = vu.RowShow;  // # of rows displayed
    int rowsMax  = vu.RowCount; // # of rows in view
    int rows     = 0;

    switch (lastKey)
    {        
      case 17:                  // Ctrl prior to Page
        rows = inc;
        break; 
      case 19:                  // Alt prior to Page
        rows = rowsMax * inc;
        break;
      default:
        rows = rowsDisp * inc
        break;
    }  // end switch

  vu.PageMove(rows)
} // end Page_Key



'----- Calling Program B4PPC, VB -----

Sub Page_Key(val,lastKey)     ' 33=PageUp, 34=Down
    inc = 1                   ' vu is DataGridView

    If val = 33 then inc = -1

    rowsDisp = vu.RowShow     ' # of rows displayed
    rowsMax  = vu.RowCount    ' # of rows in view
    rows     = 0

    Select lastKey
      Case 17                 ' Ctrl prior to Page
        rows = inc 
      Case 19                 ' Alt prior to Page
        rows = rowsMax * inc
      Case Else
        rows = rowsDisp * inc
    End Select

    lastKey = ""

    vu.PageMove(rows)
End Sub
Run Code Online (Sandbox Code Playgroud)