다음을 통해 공유


방법: Windows Forms에서 데이터 탐색

Windows 애플리케이션에서 데이터 원본의 레코드를 탐색하는 가장 쉬운 방법은 BindingSource 구성 요소를 데이터 원본에 바인딩한 다음, 컨트롤을 BindingSource에 바인딩하는 것입니다. 그런 다음, BindingSource에서 MoveNext, MoveLast, MovePrevious, MoveFirst 등의 기본 제공 탐색 메서드를 사용할 수 있습니다. 이러한 메서드를 사용하면 BindingSourcePositionCurrent 속성을 적절하게 조정할 수 있습니다. 항목을 찾고 Position 속성을 설정하여 해당 항목을 현재 항목으로 설정할 수도 있습니다.

데이터 원본에서 위치를 증분하려면

  1. 바인딩된 데이터에 대한 BindingSourcePosition 속성을 이동하려는 레코드 위치로 설정합니다. 다음 예제에서는 BindingSourceMoveNext 메서드를 사용하여 nextButton이 클릭될 때 Position 속성을 증분하는 방법을 보여 줍니다. BindingSource는 데이터 세트 NorthwindCustomers 테이블과 연결됩니다.

    참고

    .NET Framework에서는 목록 경계를 벗어난 값으로 위치를 설정할 수 없으므로 Position 속성을 첫 번째 또는 마지막 레코드를 벗어나는 값으로 설정해도 오류가 발생하지 않습니다. 애플리케이션에서 첫 번째 또는 마지막 레코드를 벗어났는지 여부를 알아야 하는 경우 데이터 요소 수를 초과할지 여부를 테스트하는 논리를 포함합니다.

    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 이벤트에 대한 이벤트 처리기를 만듭니다. 처리기에서 제안된 위치 값이 실제 데이터 요소 수를 초과했는지 여부를 테스트할 수 있습니다.

    다음 예제에서는 마지막 데이터 요소에 도달했는지 여부를 테스트하는 방법을 보여 줍니다. 이 예제에서 마지막 요소에 있다면 양식의 다음 단추를 사용할 수 없습니다.

    참고

    코드에서 탐색 중인 목록을 변경하는 경우 다음 단추를 다시 사용하도록 설정해야 사용자가 새 목록의 전체 길이를 찾아볼 수 있습니다. 또한 작업 중인 특정 BindingSource에 대한 위 PositionChanged 이벤트는 해당 이벤트 처리 메서드와 연결해야 합니다. 다음은 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를 구현하는 경우 BindingSourceFind 메서드를 사용하여 이 작업을 수행할 수 있습니다. 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
    

참고 항목