다음을 통해 공유


방법: Windows Forms DataGridView 컨트롤에 개체 바인딩

업데이트: 2007년 11월

다음 코드 예제에서는 각 개체가 개별 행으로 표시되도록 개체 컬렉션을 DataGridView 컨트롤에 바인딩하는 방법을 보여 줍니다. 콤보 상자 드롭다운 목록에 열거형 값이 포함되도록 DataGridViewComboBoxColumn에 열거형 형식을 사용하여 속성을 표시하는 방법도 보여 줍니다.

예제

Imports System.Windows.Forms
Imports System.Collections.Generic

Public Enum Title
    King
    Sir
End Enum

Public Class EnumsAndComboBox
    Inherits Form

    Private flow As New FlowLayoutPanel()
    Private WithEvents checkForChange As Button = New Button()
    Private knights As List(Of Knight)
    Private dataGridView1 As New DataGridView()

    Public Sub New()
        MyBase.New()
        SetupForm()
        SetupGrid()
    End Sub

    Private Sub SetupForm()
        AutoSize = True
    End Sub

    Private Sub SetupGrid()
        knights = New List(Of Knight)
        knights.Add(New Knight(Title.King, "Uther", True))
        knights.Add(New Knight(Title.King, "Arthur", True))
        knights.Add(New Knight(Title.Sir, "Mordred", False))
        knights.Add(New Knight(Title.Sir, "Gawain", True))
        knights.Add(New Knight(Title.Sir, "Galahad", True))

        ' Initialize the DataGridView.
        dataGridView1.AutoGenerateColumns = False
        dataGridView1.AutoSize = True
        dataGridView1.DataSource = knights

        dataGridView1.Columns.Add(CreateComboBoxWithEnums())

        ' Initialize and add a text box column.
        Dim column As DataGridViewColumn = _
            New DataGridViewTextBoxColumn()
        column.DataPropertyName = "Name"
        column.Name = "Knight"
        dataGridView1.Columns.Add(column)

        ' Initialize and add a check box column.
        column = New DataGridViewCheckBoxColumn()
        column.DataPropertyName = "GoodGuy"
        column.Name = "Good"
        dataGridView1.Columns.Add(column)

        ' Initialize the form.
        Controls.Add(dataGridView1)
        Me.AutoSize = True
        Me.Text = "DataGridView object binding demo"
    End Sub

    Private Function CreateComboBoxWithEnums() As DataGridViewComboBoxColumn
        Dim combo As New DataGridViewComboBoxColumn()
        combo.DataSource = [Enum].GetValues(GetType(Title))
        combo.DataPropertyName = "Title"
        combo.Name = "Title"
        Return combo
    End Function

#Region "business object"
    Private Class Knight
        Private hisName As String
        Private good As Boolean
        Private hisTitle As Title

        Public Sub New(ByVal title As Title, ByVal name As String, _
            ByVal good As Boolean)

            hisTitle = title
            hisName = name
            Me.good = good
        End Sub

        Public Property Name() As String
            Get
                Return hisName
            End Get

            Set(ByVal Value As String)
                hisName = Value
            End Set
        End Property

        Public Property GoodGuy() As Boolean
            Get
                Return good
            End Get
            Set(ByVal Value As Boolean)
                good = Value
            End Set
        End Property

        Public Property Title() As Title
            Get
                Return hisTitle
            End Get
            Set(ByVal Value As Title)
                hisTitle = Value
            End Set
        End Property
    End Class
#End Region

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

End Class
using System;
using System.Windows.Forms;

public enum Title
{
    King,
    Sir
};

public class EnumsAndComboBox : Form
{
    private DataGridView dataGridView1 = new DataGridView();
    private BindingSource bindingSource1 = new BindingSource();

    public EnumsAndComboBox()
    {
        this.Load += new System.EventHandler(EnumsAndComboBox_Load);
    }

    private void EnumsAndComboBox_Load(object sender, System.EventArgs e)
    {
        // Populate the data source.
        bindingSource1.Add(new Knight(Title.King, "Uther", true));
        bindingSource1.Add(new Knight(Title.King, "Arthur", true));
        bindingSource1.Add(new Knight(Title.Sir, "Mordred", false));
        bindingSource1.Add(new Knight(Title.Sir, "Gawain", true));
        bindingSource1.Add(new Knight(Title.Sir, "Galahad", true));

        // Initialize the DataGridView.
        dataGridView1.AutoGenerateColumns = false;
        dataGridView1.AutoSize = true;
        dataGridView1.DataSource = bindingSource1;

        dataGridView1.Columns.Add(CreateComboBoxWithEnums());

        // Initialize and add a text box column.
        DataGridViewColumn column = new DataGridViewTextBoxColumn();
        column.DataPropertyName = "Name";
        column.Name = "Knight";
        dataGridView1.Columns.Add(column);

        // Initialize and add a check box column.
        column = new DataGridViewCheckBoxColumn();
        column.DataPropertyName = "GoodGuy";
        column.Name = "Good";
        dataGridView1.Columns.Add(column);

        // Initialize the form.
        this.Controls.Add(dataGridView1);
        this.AutoSize = true;
        this.Text = "DataGridView object binding demo";
    }

    DataGridViewComboBoxColumn CreateComboBoxWithEnums()
    {
        DataGridViewComboBoxColumn combo = new DataGridViewComboBoxColumn();
        combo.DataSource = Enum.GetValues(typeof(Title));
        combo.DataPropertyName = "Title";
        combo.Name = "Title";
        return combo;
    }
    #region "business object"
    private class Knight
    {
        private string hisName;
        private bool good;
        private Title hisTitle;

        public Knight(Title title, string name, bool good)
        {
            hisTitle = title;
            hisName = name;
            this.good = good;
        }

        public Knight()
        {
            hisTitle = Title.Sir;
            hisName = "<enter name>";
            good = true;
        }

        public string Name
        {
            get
            {
                return hisName;
            }

            set
            {
                hisName = value;
            }
        }

        public bool GoodGuy
        {
            get
            {
                return good;
            }
            set
            {
                good = value;
            }
        }

        public Title Title
        {
            get
            {
                return hisTitle;
            }
            set
            {
                hisTitle = value;
            }
        }
    }
    #endregion

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

}

코드 컴파일

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

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

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

참고 항목

작업

방법: Windows Forms DataGridView 행에 바인딩된 개체에 액세스

참조

DataGridView

기타 리소스

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