滚动到Datagridview选定的行

5

我已经搜索了很多关于这个问题的答案,但都没有能够帮助我。我尝试使用或查看.Focus()是否适用,因为其他网站建议这样做,但不是这样。我只希望DataGridView,HistoryData.

跳到所选行。当足够的项填满网格时,它当然会跳转,但不会滚动到该行。网格上可能有我遗漏的参数吗?

下面是我的代码:

    Private Sub HistorySearch_TextChanged(sender As Object, e As EventArgs) Handles HistorySearch.TextChanged
    Try
        If HistorySearch.Text.ToString <> "" Then
            For Each HistoryRow As DataGridViewRow In HistoryData.Rows
                HistoryData.ClearSelection()
                For Each HistoryCell As DataGridViewCell In HistoryRow.Cells

                    If HistoryCell.Value.ToString.StartsWith(HistorySearch.Text.ToString) Then
                        HistoryRow.Selected = True
                        Dim i As Integer = HistoryData.CurrentRow.Index()

                    Else
                        HistoryRow.Selected = False
                    End If
                    If HistoryCell.Value.ToString.Contains(HistorySearch.Text.ToString) Then
                        HistoryRow.Selected = True
                        Dim i As Integer = HistoryData.CurrentRow.Index()
                        Return
                    Else
                        HistoryRow.Selected = False
                    End If
                Next
            Next
        End If
    Catch ex As Exception
        MsgBox(ex.Message)
    End Try
End Sub
1个回答

10

如果我理解你的问题正确,你可以使用以下任一选项滚动到DataGridView中的特定行:

CurrentCell

如果您设置DataGridViewCurrentCell,它将选择指定的单元格并滚动使该单元格可见。

例如,要选择最后一行并滚动到它:

'use suitable index, 10 is just for example
DataGridView1.CurrentCell = dataGridView1.Rows(10).Cells(0)

FirstDisplayedScrollingRowIndex

您还可以设置FirstDisplayedScrollingRowIndex来滚动到特定的行,但这并不会选择该行:

例如,仅滚动到第10行:

'use suitable index, 10 is just for example
DataGridView1.FirstDisplayedScrollingRowIndex = 10

关于解决方案#1,如果Cells(0)不可见怎么办?它会引发异常,我需要循环遍历单元格并检查第一个可见的单元格。 - Windgate

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接