Share via


如何:在 Windows 窗体中导航数据

更新:2007 年 11 月

在 Windows 应用程序中,在数据源中的记录中进行导航的最简单方式是将 BindingSource 组件绑定到数据源,然后将控件绑定到 BindingSource。然后,可以对 BindingSource 使用内置的导航方法,如 MoveNextMoveLastMovePreviousMoveFirst。使用这些方法将相应地调整 BindingSourcePositionCurrent 属性。还可以通过设置 Position 属性来查找项并将它设置为当前项。

递增在数据源中的位置

  • 将绑定数据的 BindingSourcePosition 属性设置为要转到的记录位置。下面的示例阐释在单击 nextButton 时,使用 BindingSourceMoveNext 方法递增 Position 属性。BindingSource 与数据集 Northwind 的 Customers 表相关联。

    说明:

    Position 属性设置为第一条或最后一条记录以外的值不会导致错误,因为 .NET Framework 将不允许将位置设置为列表范围之外的值。如果在应用程序中知道是否已越过第一条或最后一条记录非常重要,可包括测试是否将超过数据元素计数的逻辑。

    Private Sub nextButton_Click(ByVal sender As Object, _
        ByVal e As System.EventArgs) Handles nextButton.Click
        Me.customersBindingSource.MoveNext()
    End Sub
    
    private void nextButton_Click(object sender, System.EventArgs e)
    {
        this.customersBindingSource.MoveNext();
    }
    

检查是否已越过结尾或开始位置

  • PositionChanged 事件创建一个事件处理程序。在该处理程序中,可以测试所建议的位置值是否已超过实际数据元素计数。

    下面的示例阐释可以如何测试是否已到达了最后一个数据元素。在该示例中,如果到了最后一个元素,则窗体上的“下一页”按钮处于禁用状态。

    说明:

    请注意,如果在代码中对导航的列表进行了更改,则应重新启用“下一页”按钮,以便用户可以浏览新列表的整个长度。另外请注意,需要将要使用的特定 BindingSource 的上述 PositionChanged 事件与其事件处理方法相关联。下面是处理 PositionChanged 事件的一个方法示例:

    Sub customersBindingSource_PositionChanged(ByVal sender As Object, _
        ByVal e As EventArgs)
    
        If customersBindingSource.Position = _
            customersBindingSource.Count - 1 Then
            nextButton.Enabled = False
        Else
            nextButton.Enabled = True
        End If
    End Sub
    
    void customersBindingSource_PositionChanged(object sender, EventArgs e)
    {
        if (customersBindingSource.Position == customersBindingSource.Count - 1)
            nextButton.Enabled = false;
        else
            nextButton.Enabled = true;
    }
    

查找项并将其设置为当前项

  • 查找要设置为当前项的记录。如果数据源实现 IBindingList,则此查找操作可以通过使用 BindingSourceFind 方法来完成。实现 IBindingList 的数据源的一些示例有 BindingList<T>DataView

    Sub findButton_Click(ByVal sender As Object, ByVal e As EventArgs) _
        Handles findButton.Click
        Dim foundIndex As Integer = customersBindingSource.Find("CustomerID", _
            "ANTON")
        customersBindingSource.Position = foundIndex
    End Sub
    
    void findButton_Click(object sender, EventArgs e)
    {
        int foundIndex = customersBindingSource.Find("CustomerID", "ANTON");
        customersBindingSource.Position = foundIndex;
    }
    

请参见

概念

Windows 窗体支持的数据源

Windows 窗体数据绑定中的更改通知

数据绑定和 Windows 窗体

其他资源

Windows 窗体数据绑定