방법: Windows Forms DataGridView 컨트롤에 데이터 바인딩

DataGridView 컨트롤은 표준 Windows Forms 데이터 바인딩 모델을 지원하므로 다양한 데이터 소스에 바인딩할 수 있습니다. 일반적으로 데이터 원본과의 상호 작용을 관리하는 BindingSource에 바인딩합니다. BindingSource는 모든 Windows Forms 데이터 원본일 수 있으므로 데이터 위치를 선택하거나 수정할 때 뛰어난 유연성을 제공합니다. DataGridView 컨트롤에서 지원하는 데이터 원본에 대한 자세한 내용은 DataGridView 컨트롤 개요를 참조하세요.

Visual Studio는 DataGridView 컨트롤에 대한 데이터 바인딩을 광범위하게 지원합니다. 자세한 내용은 방법: 디자이너를 사용하여 Windows Forms DataGridView 컨트롤에 데이터 바인딩을 참조하세요.

DataGridView 컨트롤을 데이터에 연결하려면 다음을 수행합니다.

  1. 데이터를 검색하는 세부 과정을 처리하는 메서드를 구현합니다. 다음 코드 예제에서는 SqlDataAdapter를 초기화하는 GetData 메서드를 구현하고 이 메서드를 통해 DataTable을 채웁니다. 그런 다음 DataTableBindingSource에 바인딩합니다.

  2. 폼의 Load 이벤트 처리기에서 DataGridView 컨트롤을 BindingSource에 바인딩한 다음 GetData 메서드를 호출하여 데이터를 검색합니다.

예제

이 전체 코드 예제에서는 데이터베이스에서 데이터를 검색하여 DataGridView 컨트롤을 Windows 양식으로 채웁니다. 양식에는 데이터를 다시 로드하고 데이터베이스에 변경 내용을 제출하는 단추도 있습니다.

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

이 예제를 빌드하고 실행하려면 새 Windows Forms 프로젝트의 Form1 코드 파일에 코드를 붙여넣습니다. C# 또는 Visual Basic 명령줄에서 빌드하는 방법에 대한 자세한 내용은 csc.exe를 사용하여 명령줄 빌드 또는 명령줄에서 빌드를 참조하세요.

예제의 connectionString 변수를 Northwind SQL Server 샘플 데이터베이스 연결에 대한 값으로 채웁니다. 통합 보안이라고도 하는 Windows 인증은 연결 문자열에 암호를 저장하는 것보다 더 안전하게 데이터베이스에 연결하는 방법입니다. 연결 보안에 대한 자세한 내용은 연결 정보 보호를 참조하세요.

using System;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Windows.Forms;

namespace WindowsFormsApp
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
    }
}
public class Form1 : Form
{
    private DataGridView dataGridView1 = new DataGridView();
    private BindingSource bindingSource1 = new BindingSource();
    private SqlDataAdapter dataAdapter = new SqlDataAdapter();
    private Button reloadButton = new Button();
    private Button submitButton = new Button();

    [STAThread()]
    public static void Main()
    {
        Application.Run(new Form1());
    }

    // Initialize the form.
    public Form1()
    {
        dataGridView1.Dock = DockStyle.Fill;

        reloadButton.Text = "Reload";
        submitButton.Text = "Submit";
        reloadButton.Click += new EventHandler(ReloadButton_Click);
        submitButton.Click += new EventHandler(SubmitButton_Click);

        FlowLayoutPanel panel = new FlowLayoutPanel
        {
            Dock = DockStyle.Top,
            AutoSize = true
        };
        panel.Controls.AddRange(new Control[] { reloadButton, submitButton });

        Controls.AddRange(new Control[] { dataGridView1, panel });
        Load += new EventHandler(Form1_Load);
        Text = "DataGridView data binding and updating demo";
    }

    private void GetData(string selectCommand)
    {
        try
        {
            // Specify a connection string.
            // Replace <SQL Server> with the SQL Server for your Northwind sample database.
            // Replace "Integrated Security=True" with user login information if necessary.
            String connectionString =
                "Data Source=<SQL Server>;Initial Catalog=Northwind;" +
                "Integrated Security=True";

            // Create a new data adapter based on the specified query.
            dataAdapter = new SqlDataAdapter(selectCommand, connectionString);

            // Create a command builder to generate SQL update, insert, and
            // delete commands based on selectCommand.
            SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);

            // Populate a new data table and bind it to the BindingSource.
            DataTable table = new DataTable
            {
                Locale = CultureInfo.InvariantCulture
            };
            dataAdapter.Fill(table);
            bindingSource1.DataSource = table;

            // Resize the DataGridView columns to fit the newly loaded content.
            dataGridView1.AutoResizeColumns(
                DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader);
        }
        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 void Form1_Load(object sender, EventArgs e)
    {
        // Bind the DataGridView to the BindingSource
        // and load the data from the database.
        dataGridView1.DataSource = bindingSource1;
        GetData("select * from Customers");
    }

    private void ReloadButton_Click(object sender, EventArgs e)
    {
        // Reload the data from the database.
        GetData(dataAdapter.SelectCommand.CommandText);
    }

    private void SubmitButton_Click(object sender, EventArgs e)
    {
        // Update the database with changes.
        dataAdapter.Update((DataTable)bindingSource1.DataSource);
    }
}
Imports System.Data.SqlClient
Imports System.Windows.Forms

Public Class Form1
    Inherits Form

    Private dataGridView1 As New DataGridView()
    Private bindingSource1 As New BindingSource()
    Private dataAdapter As New SqlDataAdapter()
    Private WithEvents ReloadButton As New Button()
    Private WithEvents SubmitButton As New Button()

    Public Shared Sub Main()
        Application.Run(New Form1())
    End Sub

    ' Initialize the form.
    Public Sub New()

        dataGridView1.Dock = DockStyle.Fill

        ReloadButton.Text = "Reload"
        SubmitButton.Text = "Submit"

        Dim panel As New FlowLayoutPanel With {
            .Dock = DockStyle.Top,
            .AutoSize = True
        }
        panel.Controls.AddRange(New Control() {ReloadButton, SubmitButton})

        Controls.AddRange(New Control() {dataGridView1, panel})
        Text = "DataGridView data binding and updating demo"

    End Sub

    Private Sub GetData(ByVal selectCommand As String)

        Try
            ' Specify a connection string.  
            ' Replace <SQL Server> with the SQL Server for your Northwind sample database.
            ' Replace "Integrated Security=True" with user login information if necessary.
            Dim connectionString As String =
                "Data Source=<SQL Server>;Initial Catalog=Northwind;" +
                "Integrated Security=True;"

            ' Create a new data adapter based on the specified query.
            dataAdapter = New SqlDataAdapter(selectCommand, connectionString)

            ' Create a command builder to generate SQL update, insert, and
            ' delete commands based on selectCommand. 
            Dim commandBuilder As New SqlCommandBuilder(dataAdapter)

            ' Populate a new data table and bind it to the BindingSource.
            Dim table As New DataTable With {
                .Locale = Globalization.CultureInfo.InvariantCulture
            }
            dataAdapter.Fill(table)
            bindingSource1.DataSource = table

            ' Resize the DataGridView columns to fit the newly loaded content.
            dataGridView1.AutoResizeColumns(
                DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader)

        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 Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) _
        Handles Me.Load

        ' Bind the DataGridView to the BindingSource
        ' and load the data from the database.
        dataGridView1.DataSource = bindingSource1
        GetData("select * from Customers")

    End Sub

    Private Sub ReloadButton_Click(ByVal sender As Object, ByVal e As EventArgs) _
        Handles ReloadButton.Click

        ' Reload the data from the database.
        GetData(dataAdapter.SelectCommand.CommandText)

    End Sub

    Private Sub SubmitButton_Click(ByVal sender As Object, ByVal e As EventArgs) _
        Handles SubmitButton.Click

        ' Update the database with changes.
        dataAdapter.Update(CType(bindingSource1.DataSource, DataTable))

    End Sub

End Class

참고 항목