如何:巡覽 Windows Form 中的資料

在 Windows 應用程式中,流覽資料來源中記錄的最簡單方式是將元件系結 BindingSource 至資料來源,然後將控制項系結至 BindingSource 。 接著,您可以在這類 MoveNextMovePreviousMoveLastMoveFirst 上使用 BindingSource 內建導覽方法。 使用這些方法會適當地調整 PositionBindingSourceCurrent 屬性。 您也可以藉由設定 Position 屬性來尋找專案,並將其設定為目前的專案。

若要遞增資料來源中的位置

  1. Position 系結資料的 屬性 BindingSource 設定為要移至的記錄位置。 下列範例說明在按一下 時 nextButton ,使用 MoveNextBindingSource 方法來遞增 Position 屬性。 與 BindingSource 資料集 Northwind 的資料表相關聯 Customers

    注意

    Position 屬性設定為超出第一筆或最後一筆記錄的值不會產生錯誤,因為 .NET Framework 不會允許您將位置設定為超出清單界限的值。 如果您的應用程式中務必知道您是否已經超過第一筆或最後一筆記錄,請包含邏輯來測試您是否將超過資料元素計數。

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

檢查您是否已經結束或開始

  1. 建立 PositionChanged 事件的事件處理常式。 在處理常式中,您可以測試建議的位置值是否已超過實際的資料元素計數。

    下列範例說明如何測試您是否已到達最後一個資料元素。 在此範例中,如果您位於最後一個專案, 表單上的 [下一步 ] 按鈕會停用。

    注意

    請注意,如果您變更要在程式碼中流覽的清單,您應該重新啟用 [ 下一步 ] 按鈕,讓使用者可以流覽新清單的整個長度。 此外,請注意,您 PositionChanged 正在使用的特定 BindingSource 事件必須與其事件處理方法相關聯。 以下是處理 PositionChanged 事件的方法範例:

    void customersBindingSource_PositionChanged(object sender, EventArgs e)
    {
        if (customersBindingSource.Position == customersBindingSource.Count - 1)
            nextButton.Enabled = false;
        else
            nextButton.Enabled = true;
    }
    
    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
    

若要尋找專案,並將它設定為目前專案

  1. 尋找您想要設定為目前專案的記錄。 如果您的資料來源實作 IBindingList ,您可以使用 的 BindingSource 方法執行這項 Find 操作。 實 IBindingList 作 的資料來源範例為 BindingList<T>DataView

    void findButton_Click(object sender, EventArgs e)
    {
        int foundIndex = customersBindingSource.Find("CustomerID", "ANTON");
        customersBindingSource.Position = foundIndex;
    }
    
    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
    

另請參閱