Share via


HOW TO:巡覽 Windows Form 中的資料

在 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 方法,即可達到此目的。 例如 BindingList<T>DataView 就是資料來源實作 IBindingList 的範例。

    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 Form 支援的資料來源

Windows Form 資料繫結中的變更告知

資料繫結和 Windows Form

其他資源

Windows Form 資料繫結