다음을 통해 공유


연습: 두 개의 Windows Forms DataGridView 컨트롤을 사용하여 마스터/세부 폼 만들기

업데이트: 2007년 11월

DataGridView 컨트롤을 사용하는 가장 일반적인 시나리오 중 하나는 두 데이터베이스 테이블의 부모/자식 관계가 표시되는 마스터/세부 폼입니다. 마스터 테이블에서 행을 선택하면 세부 테이블이 해당 자식 데이터를 사용하여 업데이트됩니다.

마스터/세부 폼은 DataGridView 컨트롤과 BindingSource 구성 요소의 상호 작용을 사용하여 쉽게 구현할 수 있습니다. 이 연습에서는 두 개의 DataGridView 컨트롤과 두 개의 BindingSource 구성 요소를 사용하여 폼을 만듭니다. 이 폼에는 Northwind SQL Server 샘플 데이터베이스에 있는 Customers와 Orders라는 두 개의 관련 테이블이 표시됩니다. 연습을 모두 완료하면 데이터베이스의 모든 고객이 마스터 DataGridView에 표시되고 선택한 고객의 모든 주문이 세부 DataGridView에 표시됩니다.

이 항목의 코드를 단일 목록으로 복사하려면 방법: 두 개의 Windows Forms DataGridView 컨트롤을 사용하여 마스터/세부 폼 만들기를 참조하십시오.

사전 요구 사항

이 연습을 따라 하려면 다음과 같은 요건을 갖추어야 합니다.

  • Northwind SQL Server 샘플 데이터베이스가 있는 서버에 액세스할 수 있어야 합니다.

폼 만들기

마스터/세부 폼을 만들려면

  1. Form에서 파생되고 두 개의 DataGridView 컨트롤과 두 개의 BindingSource 구성 요소를 포함하는 클래스를 만듭니다. 다음 코드는 기본 폼 초기화를 제공하고 Main 메서드를 포함합니다. Visual Studio 디자이너를 사용하여 폼을 만들 경우 이 코드 대신 디자이너 생성 코드를 사용할 수 있습니다. 그럴 경우에는 이 코드의 변수 선언에 표시된 이름을 사용해야 합니다.

    Imports System
    Imports System.Data
    Imports System.Data.SqlClient
    Imports System.Windows.Forms
    
    Public Class Form1
        Inherits System.Windows.Forms.Form
    
        Private masterDataGridView As New DataGridView()
        Private masterBindingSource As New BindingSource()
        Private detailsDataGridView As New DataGridView()
        Private detailsBindingSource As New BindingSource()
    
        <STAThreadAttribute()> _
        Public Shared Sub Main()
            Application.Run(New Form1())
        End Sub
    
        ' Initializes the form.
        Public Sub New()
    
            masterDataGridView.Dock = DockStyle.Fill
            detailsDataGridView.Dock = DockStyle.Fill
    
            Dim splitContainer1 As New SplitContainer()
            splitContainer1.Dock = DockStyle.Fill
            splitContainer1.Orientation = Orientation.Horizontal
            splitContainer1.Panel1.Controls.Add(masterDataGridView)
            splitContainer1.Panel2.Controls.Add(detailsDataGridView)
    
            Me.Controls.Add(splitContainer1)
            Me.Text = "DataGridView master/detail demo"
    
        End Sub
    
    
    ...
    
    
    End Class
    
    using System;
    using System.Data;
    using System.Data.SqlClient;
    using System.Windows.Forms;
    
    public class Form1 : System.Windows.Forms.Form
    {
        private DataGridView masterDataGridView = new DataGridView();
        private BindingSource masterBindingSource = new BindingSource();
        private DataGridView detailsDataGridView = new DataGridView();
        private BindingSource detailsBindingSource = new BindingSource();
    
        [STAThreadAttribute()]
        public static void Main()
        {
            Application.Run(new Form1());
        }
    
        // Initializes the form.
        public Form1()
        {
            masterDataGridView.Dock = DockStyle.Fill;
            detailsDataGridView.Dock = DockStyle.Fill;
    
            SplitContainer splitContainer1 = new SplitContainer();
            splitContainer1.Dock = DockStyle.Fill;
            splitContainer1.Orientation = Orientation.Horizontal;
            splitContainer1.Panel1.Controls.Add(masterDataGridView);
            splitContainer1.Panel2.Controls.Add(detailsDataGridView);
    
            this.Controls.Add(splitContainer1);
            this.Load += new System.EventHandler(Form1_Load);
            this.Text = "DataGridView master/detail demo";
        }
    
    
    ...
    
    
    }
    
  2. 데이터베이스에 연결하는 데 필요한 세부 사항을 처리할 수 있도록 메서드를 폼의 클래스 정의에 구현합니다. 이 예제에서는 GetData 메서드를 사용하여 DataSet 개체를 채우고 DataRelation 개체를 데이터 집합에 추가한 다음 BindingSource 구성 요소를 바인딩합니다. connectionString 변수를 데이터베이스에 해당하는 값으로 설정해야 합니다.

    보안 정보:

    연결 문자열에 중요한 정보(예: 암호)를 저장하면 응용 프로그램 보안 문제가 발생할 수 있습니다. 데이터베이스 액세스를 제어할 경우에는 통합 보안이라고도 하는 Windows 인증을 사용하는 방법이 더 안전합니다. 자세한 내용은 연결 정보 보호(ADO.NET)를 참조하십시오.

    Private Sub GetData()
    
        Try
            ' Specify a connection string. Replace the given value with a 
            ' valid connection string for a Northwind SQL Server sample
            ' database accessible to your system.
            Dim connectionString As String = _
                "Integrated Security=SSPI;Persist Security Info=False;" & _
                "Initial Catalog=Northwind;Data Source=localhost"
            Dim connection As New SqlConnection(connectionString)
    
            ' Create a DataSet.
            Dim data As New DataSet()
            data.Locale = System.Globalization.CultureInfo.InvariantCulture
    
            ' Add data from the Customers table to the DataSet.
            Dim masterDataAdapter As _
                New SqlDataAdapter("select * from Customers", connection)
            masterDataAdapter.Fill(data, "Customers")
    
            ' Add data from the Orders table to the DataSet.
            Dim detailsDataAdapter As _
                New SqlDataAdapter("select * from Orders", connection)
            detailsDataAdapter.Fill(data, "Orders")
    
            ' Establish a relationship between the two tables.
            Dim relation As New DataRelation("CustomersOrders", _
                data.Tables("Customers").Columns("CustomerID"), _
                data.Tables("Orders").Columns("CustomerID"))
            data.Relations.Add(relation)
    
            ' Bind the master data connector to the Customers table.
            masterBindingSource.DataSource = data
            masterBindingSource.DataMember = "Customers"
    
            ' Bind the details data connector to the master data connector,
            ' using the DataRelation name to filter the information in the 
            ' details table based on the current row in the master table. 
            detailsBindingSource.DataSource = masterBindingSource
            detailsBindingSource.DataMember = "CustomersOrders"
        Catch ex As SqlException
            MessageBox.Show("To run this example, replace the value of the " & _
                "connectionString variable with a connection string that is " & _
                "valid for your system.")
        End Try
    
    End Sub
    
    private void GetData()
    {
        try
        {
            // Specify a connection string. Replace the given value with a 
            // valid connection string for a Northwind SQL Server sample
            // database accessible to your system.
            String connectionString =
                "Integrated Security=SSPI;Persist Security Info=False;" +
                "Initial Catalog=Northwind;Data Source=localhost";
            SqlConnection connection = new SqlConnection(connectionString);
    
            // Create a DataSet.
            DataSet data = new DataSet();
            data.Locale = System.Globalization.CultureInfo.InvariantCulture;
    
            // Add data from the Customers table to the DataSet.
            SqlDataAdapter masterDataAdapter = new
                SqlDataAdapter("select * from Customers", connection);
            masterDataAdapter.Fill(data, "Customers");
    
            // Add data from the Orders table to the DataSet.
            SqlDataAdapter detailsDataAdapter = new
                SqlDataAdapter("select * from Orders", connection);
            detailsDataAdapter.Fill(data, "Orders");
    
            // Establish a relationship between the two tables.
            DataRelation relation = new DataRelation("CustomersOrders",
                data.Tables["Customers"].Columns["CustomerID"],
                data.Tables["Orders"].Columns["CustomerID"]);
            data.Relations.Add(relation);
    
            // Bind the master data connector to the Customers table.
            masterBindingSource.DataSource = data;
            masterBindingSource.DataMember = "Customers";
    
            // Bind the details data connector to the master data connector,
            // using the DataRelation name to filter the information in the 
            // details table based on the current row in the master table. 
            detailsBindingSource.DataSource = masterBindingSource;
            detailsBindingSource.DataMember = "CustomersOrders";
        }
        catch (SqlException)
        {
            MessageBox.Show("To run this example, replace the value of the " +
                "connectionString variable with a connection string that is " +
                "valid for your system.");
        }
    }
    
  3. DataGridView 컨트롤을 BindingSource 구성 요소에 바인딩하고 GetData 메서드를 호출하도록 폼의 Load 이벤트 처리기를 구현합니다. 다음 예제에는 표시된 데이터에 맞게 DataGridView 열의 크기를 조정하는 코드가 들어 있습니다.

    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) _
        Handles Me.Load
    
        ' Bind the DataGridView controls to the BindingSource
        ' components and load the data from the database.
        masterDataGridView.DataSource = masterBindingSource
        detailsDataGridView.DataSource = detailsBindingSource
        GetData()
    
        ' Resize the master DataGridView columns to fit the newly loaded data.
        masterDataGridView.AutoResizeColumns()
    
        ' Configure the details DataGridView so that its columns automatically
        ' adjust their widths when the data changes.
        detailsDataGridView.AutoSizeColumnsMode = _
            DataGridViewAutoSizeColumnsMode.AllCells
    
    End Sub
    
    private void Form1_Load(object sender, System.EventArgs e)
    {
        // Bind the DataGridView controls to the BindingSource
        // components and load the data from the database.
        masterDataGridView.DataSource = masterBindingSource;
        detailsDataGridView.DataSource = detailsBindingSource;
        GetData();
    
        // Resize the master DataGridView columns to fit the newly loaded data.
        masterDataGridView.AutoResizeColumns();
    
        // Configure the details DataGridView so that its columns automatically
        // adjust their widths when the data changes.
        detailsDataGridView.AutoSizeColumnsMode = 
            DataGridViewAutoSizeColumnsMode.AllCells;
    }
    

응용 프로그램 테스트

이제 폼을 테스트하여 예상한 대로 동작하는지 확인할 수 있습니다.

폼을 테스트하려면

  • 응용 프로그램을 컴파일하여 실행합니다.

    두 개의 DataGridView 컨트롤이 위아래로 나란히 표시됩니다. 위쪽 컨트롤에는 Northwind Customers 테이블에 있는 고객이 표시되고, 아래쪽 컨트롤에는 선택한 고객에 해당하는 Orders가 표시됩니다. 위쪽 DataGridView에서 다른 행을 선택하면 그에 따라 아래쪽 DataGridView의 내용이 바뀝니다.

다음 단계

이 응용 프로그램은 DataGridView 컨트롤의 기능에 대한 기본적인 이해를 제공합니다. 다음과 같은 여러 가지 방법으로 DataGridView 컨트롤의 모양과 동작을 사용자 지정할 수 있습니다.

참고 항목

작업

방법: 두 개의 Windows Forms DataGridView 컨트롤을 사용하여 마스터/세부 폼 만들기

개념

연결 정보 보호(ADO.NET)

참조

DataGridView

BindingSource

기타 리소스

Windows Forms DataGridView 컨트롤에서 데이터 표시