다음을 통해 공유


방법: 팩터리 개체에 Windows Forms 컨트롤 바인딩

데이터와 상호 작용하는 컨트롤을 작성할 때 다른 개체를 생성하는 메서드나 개체에 컨트롤을 바인딩해야 하는 경우가 가끔 있습니다. 이러한 개체나 메서드를 팩터리라고 합니다. 예를 들어, 데이터 소스가 메모리의 개체나 형식 대신 메서드 호출의 반환 값일 수 있습니다. 소스에서 컬렉션을 반환하면 이러한 종류의 데이터 소스에 컨트롤을 바인딩할 수 있습니다.

BindingSource 컨트롤을 사용하면 팩터리 개체에 컨트롤을 쉽게 바인딩할 수 있습니다.

예제

다음 예제에서는 BindingSource 컨트롤을 사용하여 팩터리 메서드에 DataGridView 컨트롤을 바인딩하는 방법을 보여 줍니다. 팩터리 메서드는 이름이 GetOrdersByCustomerId이며 Northwind 데이터베이스에서 지정된 고객에 대한 모든 주문을 반환합니다.

Imports System
Imports System.Collections
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Data
Imports System.Data.Common
Imports System.Diagnostics
Imports System.Drawing
Imports System.Data.SqlClient
Imports System.Windows.Forms

' This form demonstrates using a BindingSource to bind to a factory
' object. 

Public Class Form1
    Inherits System.Windows.Forms.Form
    ' This is the TextBox for entering CustomerID values.
    Private WithEvents customerIdTextBox As New TextBox()

    ' This is the DataGridView that displays orders for the 
    ' specified customer.
    Private customersDataGridView As New DataGridView()

    ' This is the BindingSource for binding the database query
    ' result set to the DataGridView.
    Private ordersBindingSource As New BindingSource()

    Public Sub New() 

        ' Set up the CustomerID TextBox.
        Me.customerIdTextBox.Location = New Point(100, 200)
        Me.customerIdTextBox.Size = New Size(500, 30)
        Me.customerIdTextBox.Text = _
            "Enter a valid Northwind CustomerID, for example: ALFKI," & _
            " then RETURN or click outside the TextBox"
        Me.Controls.Add(Me.customerIdTextBox)

        ' Set up the DataGridView.
        customersDataGridView.Dock = DockStyle.Top
        Me.Controls.Add(customersDataGridView)

        ' Set up the form.
        Me.Size = New Size(800, 500)
    End Sub

    ' This event handler binds the BindingSource to the DataGridView
    ' control's DataSource property.
    Private Sub Form1_Load(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles Me.Load

        ' Attach the BindingSource to the DataGridView.
        Me.customersDataGridView.DataSource = Me.ordersBindingSource

    End Sub

    ' This is a static factory method. It queries the Northwind 
    ' database for the orders belonging to the specified
    ' customer and returns an IEnumerable.
    Public Shared Function GetOrdersByCustomerId(ByVal id As String) _
        As IEnumerable

        ' Open a connection to the database.
        Dim connectString As String = "Integrated Security=SSPI;" & _
             "Persist Security Info=False;Initial Catalog=Northwind;" & _
             "Data Source= localhost"
        Dim connection As New SqlConnection()

        connection.ConnectionString = connectString
        connection.Open()

        ' Execute the query.
        Dim queryString As String = _
            String.Format("Select * From Orders where CustomerID = '{0}'", id)
        Dim command As New SqlCommand(queryString, connection)
        Dim reader As SqlDataReader = _
            command.ExecuteReader(CommandBehavior.CloseConnection)
        Return reader

    End Function

    ' These event handlers are called when the user tabs or clicks
    ' out of the customerIdTextBox or hits the return key.
    ' The database is then queried with the CustomerID
    '  in the customerIdTextBox.Text property.
    Private Sub customerIdTextBox_Leave(ByVal sender As Object, _
        ByVal e As EventArgs) Handles customerIdTextBox.Leave

        ' Attach the data source to the BindingSource control.
        Me.ordersBindingSource.DataSource = _
            GetOrdersByCustomerId(Me.customerIdTextBox.Text)

    End Sub


    Private Sub customerIdTextBox_KeyDown(ByVal sender As Object, _
        ByVal e As KeyEventArgs) Handles customerIdTextBox.KeyDown

        If e.KeyCode = Keys.Return Then

            ' Attach the data source to the BindingSource control.
            Me.ordersBindingSource.DataSource = _
                GetOrdersByCustomerId(Me.customerIdTextBox.Text)
        End If

    End Sub

    <STAThread()> _
    Shared Sub Main()
        Application.EnableVisualStyles()
        Application.Run(New Form1())

    End Sub
End Class
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Diagnostics;
using System.Drawing;
using System.Data.SqlClient;
using System.Windows.Forms;

// This form demonstrates using a BindingSource to bind to a factory
// object. 
public class Form1 : System.Windows.Forms.Form
{
    // This is the TextBox for entering CustomerID values.
    private TextBox customerIdTextBox = new TextBox();

    // This is the DataGridView that displays orders for the 
    // specified customer.
    private DataGridView customersDataGridView = new DataGridView();

    // This is the BindingSource for binding the database query
    // result set to the DataGridView.
    private BindingSource ordersBindingSource = new BindingSource();

    public Form1()
    {
        // Set up the CustomerID TextBox.
        this.customerIdTextBox.Location = new Point(100, 200);
        this.customerIdTextBox.Size = new Size(500, 30);
        this.customerIdTextBox.Text =
            "Enter a valid Northwind CustomerID, for example: ALFKI," +
            " then RETURN or click outside the TextBox";
        this.customerIdTextBox.Leave +=
            new EventHandler(customerIdTextBox_Leave);
        this.customerIdTextBox.KeyDown +=
            new KeyEventHandler(customerIdTextBox_KeyDown);
        this.Controls.Add(this.customerIdTextBox);

        // Set up the DataGridView.
        customersDataGridView.Dock = DockStyle.Top;
        this.Controls.Add(customersDataGridView);

        // Set up the form.
        this.Size = new Size(800, 500);
        this.Load += new EventHandler(Form1_Load);
    }

    // This event handler binds the BindingSource to the DataGridView
    // control's DataSource property.
    private void Form1_Load(
        System.Object sender,
        System.EventArgs e)
    {
        // Attach the BindingSource to the DataGridView.
        this.customersDataGridView.DataSource =
            this.ordersBindingSource;
    }

    // This is a static factory method. It queries the Northwind 
    // database for the orders belonging to the specified
    // customer and returns an IEnumerable.
    public static IEnumerable GetOrdersByCustomerId(string id)
    {
        // Open a connection to the database.
        string connectString = "Integrated Security=SSPI;" +
            "Persist Security Info=False;Initial Catalog=Northwind;" +
            "Data Source= localhost";
        SqlConnection connection = new SqlConnection();

        connection.ConnectionString = connectString;
        connection.Open();

        // Execute the query.
        string queryString =
            String.Format("Select * From Orders where CustomerID = '{0}'",
            id);
        SqlCommand command = new SqlCommand(queryString, connection);
        SqlDataReader reader =
            command.ExecuteReader(CommandBehavior.CloseConnection);
        return reader;

    }

    // These event handlers are called when the user tabs or clicks
    // out of the customerIdTextBox or hits the return key.
    // The database is then queried with the CustomerID
    //  in the customerIdTextBox.Text property.
    void customerIdTextBox_Leave(object sender, EventArgs e)
    {
        // Attach the data source to the BindingSource control.
        this.ordersBindingSource.DataSource =
            GetOrdersByCustomerId(this.customerIdTextBox.Text);
    }

    void customerIdTextBox_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Return)
        {
            // Attach the data source to the BindingSource control.
            this.ordersBindingSource.DataSource =
                GetOrdersByCustomerId(this.customerIdTextBox.Text);
        }
    }

    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.Run(new Form1());
    }
}
#using <System.dll>
#using <System.Data.dll>
#using <System.Drawing.dll>
#using <System.EnterpriseServices.dll>
#using <System.Transactions.dll>
#using <System.Windows.Forms.dll>
#using <System.Xml.dll>
using namespace System;
using namespace System::Collections;
using namespace System::Collections::Generic;
using namespace System::ComponentModel;
using namespace System::Data;
using namespace System::Data::Common;
using namespace System::Data::SqlClient;
using namespace System::Diagnostics;
using namespace System::Drawing;
using namespace System::Windows::Forms;

// This form demonstrates using a BindingSource to bind to a factory
// object.
public ref class Form1: public System::Windows::Forms::Form
{
private:

   // This is the TextBox for entering CustomerID values.
   static TextBox^ customerIdTextBox = gcnew TextBox;

   // This is the DataGridView that displays orders for the
   // specified customer.
   static DataGridView^ customersDataGridView = gcnew DataGridView;

   // This is the BindingSource for binding the database query
   // result set to the DataGridView.
   static BindingSource^ ordersBindingSource = gcnew BindingSource;

public:
   Form1()
   {
      // Set up the CustomerID TextBox.
      this->customerIdTextBox->Dock = DockStyle::Bottom;
      this->customerIdTextBox->Text =
         L"Enter a valid Northwind CustomerID, for example: ALFKI,"

      L" then TAB or click outside the TextBox";
      this->customerIdTextBox->Leave += gcnew EventHandler(
         this, &Form1::customerIdTextBox_Leave );
      this->Controls->Add( this->customerIdTextBox );

      // Set up the DataGridView.
      customersDataGridView->Dock = DockStyle::Top;
      this->Controls->Add( customersDataGridView );

      // Set up the form.
      this->Size = System::Drawing::Size( 800, 800 );
      this->Load += gcnew EventHandler( this, &Form1::Form1_Load );
   }

private:
   // This event handler binds the BindingSource to the DataGridView
   // control's DataSource property.
   void Form1_Load(
      System::Object^ /*sender*/,
      System::EventArgs^ /*e*/ )
   {
      // Attach the BindingSource to the DataGridView.
      this->customersDataGridView->DataSource =
         this->ordersBindingSource;
   }

public:
   // This is a static factory method. It queries the Northwind
   // database for the orders belonging to the specified
   // customer and returns an IList.
   static System::Collections::IList^ GetOrdersByCustomerId( String^ id )
   {
      // Open a connection to the database.
      String^ connectString = L"Integrated Security=SSPI;"
      L"Persist Security Info=False;Initial Catalog=Northwind;"
      L"Data Source= localhost";
      SqlConnection^ connection = gcnew SqlConnection;
      connection->ConnectionString = connectString;
      connection->Open();

      // Execute the query.
      String^ queryString = String::Format(
         L"Select * From Orders where CustomerID = '{0}'", id );
      SqlCommand^ command = gcnew SqlCommand( queryString,connection );
      SqlDataReader^ reader = command->ExecuteReader(
         CommandBehavior::CloseConnection );

      // Build an IList from the result set.
      List< DbDataRecord^ >^ list = gcnew List< DbDataRecord^ >;
      System::Collections::IEnumerator^ e = reader->GetEnumerator();
      while ( e->MoveNext() )
      {
         list->Add( dynamic_cast<DbDataRecord^>(e->Current) );
      }

      return list;
   }

   // This event handler is called when the user tabs or clicks
   // out of the customerIdTextBox. The database is then queried
   // with the CustomerID in the customerIdTextBox.Text property.
private:
   void customerIdTextBox_Leave( Object^ /*sender*/, EventArgs^ /*e*/ )
   {
      // Attach the data source to the BindingSource control.
      this->ordersBindingSource->DataSource = GetOrdersByCustomerId(
         this->customerIdTextBox->Text );
   }

public:
   [STAThread]
   static void main()
   {
      Application::EnableVisualStyles();
      Application::Run( gcnew Form1 );
   }
};

코드 컴파일

이 예제에는 다음 사항이 필요합니다.

  • System, System.Data, System.Drawing 및 System.Windows.Forms 어셈블리에 대한 참조

Visual Basic 또는 Visual C#의 명령줄에서 이 예제를 빌드하는 방법에 대한 자세한 내용은 명령줄에서 빌드(Visual Basic) 또는 csc.exe를 사용한 명령줄 빌드를 참조하십시오. Visual Studio에서 코드를 새 프로젝트에 붙여넣어 이 예제를 빌드할 수도 있습니다. 자세한 내용은 다음을 참조하십시오. 방법: Visual Studio를 사용하여 전체 Windows Forms 코드 예제 컴파일 및 실행방법: Visual Studio를 사용하여 전체 Windows Forms 코드 예제 컴파일 및 실행방법: Visual Studio를 사용하여 전체 Windows Forms 코드 예제 컴파일 및 실행방법: Visual Studio를 사용하여 전체 Windows Forms 코드 예제 컴파일 및 실행방법: Visual Studio를 사용하여 전체 Windows Forms 코드 예제 컴파일 및 실행.

참고 항목

작업

방법: 형식에 Windows Forms 컨트롤 바인딩

참조

BindingNavigator

DataGridView

BindingSource

기타 리소스

BindingSource 구성 요소