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

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

마스터/세부 정보 형식을 구현하는 것은 DataGridView 컨트롤과 BindingSource 구성 요소 간의 상호 작용을 쉽게 사용할 수 있습니다. 이 연습에서는 두 개의 DataGridView 컨트롤과 두 개의 BindingSource 구성 요소를 사용하여 양식을 작성합니다. 양식은 Northwind SQL Server 샘플 데이터베이스에 두 개의 관련 테이블(CustomersOrders)을 표시합니다. 완료되면 마스터 DataGridView의 데이터베이스에 있는 모든 고객과 상세 DataGridView에서 선택한 고객에 대한 모든 주문을 표시하는 양식이 있습니다.

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

사전 요구 사항

이 연습을 완료하려면 다음 사항이 필요합니다.

  • Northwind SQL Server 샘플 데이터베이스가 있는 서버에 대한 액세스 권한.

양식 만들기

마스터/세부 정보 양식을 만들려면

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

    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";
        }
    
    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
    
  2. 데이터베이스에 연결하는 세부 정보를 처리하기 위해 양식의 클래스 정의에 메서드를 구현합니다. 이 예제에서는 DataSet 개체를 채우고, 데이터 집합에 DataRelation 개체를 추가하고, BindingSource 구성 요소를 바인딩하는 GetData 메서드를 사용합니다. connectionString 변수를 사용자의 데이터베이스에 적합한 값으로 설정해야 합니다.

    중요

    암호와 같은 중요한 정보를 연결 문자열 내에 저장하면 애플리케이션 보안 문제가 발생할 수 있습니다. 데이터베이스 액세스를 제어할 경우에는 통합 보안이라고도 하는 Windows 인증을 사용하는 방법이 더 안전합니다. 자세한 내용은 연결 정보 보호를 참조하세요.

    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.");
        }
    }
    
    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
    
  3. DataGridView 컨트롤을 BindingSource 구성 요소에 바인딩하고 GetData 메서드를 호출하는 폼 Load 이벤트에 대한 처리기를 구현합니다. 다음 예제에는 표시된 데이터에 맞게 DataGridView 열의 크기를 조정하는 코드가 포함되어 있습니다.

    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;
    }
    
    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
    

애플리케이션 테스트

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

양식 테스트

  • 애플리케이션을 컴파일하고 실행합니다.

    두 개의 DataGridView 컨트롤이 다른 컨트롤 위에 표시됩니다. 맨 위에는 Northwind Customers 테이블의 고객이 있으며, 맨 아래에는 선택한 고객에 해당하는 고객이 Orders이(가) 있습니다. 위쪽 DataGridView에서 다른 행을 선택하면 아래쪽 DataGridView의 내용이 그에 따라 변경됩니다.

다음 단계

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

참고 항목