다음을 통해 공유


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

업데이트: 2007년 11월

비즈니스 개체 컬렉션에 저장된 정보 테이블을 표시하는 것이 좋은 경우도 있습니다. DataGridView 컨트롤을 이런 컬렉션에 바인딩할 때 각 공용 속성은 BrowsableAttribute에 non-browsable로 표시되어 있지 않는 한 해당 열에 표시됩니다. 예를 들어, Customer 개체 컬렉션에는 Name, Address 등의 열이 있습니다.

이러한 개체에 액세스하려는 추가 정보와 코드가 있는 경우 행 개체를 사용하여 액세스할 수 있습니다. 다음 코드 예제에서는 여러 행을 선택한 다음 단추를 클릭하여 송장을 각 해당 고객에게 보낼 수 있습니다.

행 바인딩된 개체에 액세스하려면

  • DataGridViewRow.DataBoundItem 속성을 사용합니다.

    Private Sub InvoiceButton_Click(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles InvoiceButton.Click
    
        For Each row As DataGridViewRow In Me.DataGridView1.SelectedRows
    
            Dim cust As Customer = TryCast(row.DataBoundItem, Customer)
            If cust IsNot Nothing Then
                cust.SendInvoice()
            End If
    
        Next
    
    End Sub
    
    void invoiceButton_Click(object sender, EventArgs e)
    {
        foreach (DataGridViewRow row in this.dataGridView1.SelectedRows)
        {
            Customer cust = row.DataBoundItem as Customer;
            if (cust != null)
            {
                cust.SendInvoice();
            }
        }
    }
    

예제

전체 코드 예제에는 간단한 Customer 구현이 포함되어 있으며 DataGridView를 일부 Customer 개체를 포함하는 ArrayList에 바인딩합니다. Form.Load 이벤트 처리기 외부에서 고객 컬렉션에 액세스할 수 없기 때문에 System.Windows.Forms.ButtonClick 이벤트 처리기에서 행을 통해 Customer 개체에 액세스해야 합니다.

Imports System
Imports System.Windows.Forms

Public Class DataGridViewObjectBinding
    Inherits Form

    ' These declarations and the Main() and New() methods 
    ' below can be replaced with designer-generated code. 
    Private WithEvents InvoiceButton As New Button()
    Private WithEvents DataGridView1 As New DataGridView()

    ' Entry point code. 
    <STAThreadAttribute()> _
    Public Shared Sub Main()

        Application.Run(New DataGridViewObjectBinding())

    End Sub

    ' Sets up the form. 
    Public Sub New()

        Me.DataGridView1.Dock = DockStyle.Fill
        Me.Controls.Add(Me.DataGridView1)

        Me.InvoiceButton.Text = "invoice the selected customers"
        Me.InvoiceButton.Dock = DockStyle.Top
        Me.Controls.Add(Me.InvoiceButton)
        Me.Text = "DataGridView collection-binding demo"

    End Sub

    Private Sub Form1_Load(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles MyBase.Load

        ' Set up a collection of objects for binding.
        Dim customers As New System.Collections.ArrayList()
        customers.Add(New Customer("Harry"))
        customers.Add(New Customer("Sally"))
        customers.Add(New Customer("Roy"))
        customers.Add(New Customer("Pris"))

        ' Initialize and bind the DataGridView.
        Me.DataGridView1.SelectionMode = _
            DataGridViewSelectionMode.FullRowSelect
        Me.DataGridView1.AutoGenerateColumns = True
        Me.DataGridView1.DataSource = customers

    End Sub

    ' Calls the SendInvoice() method for the Customer 
    ' object bound to each selected row.
    Private Sub InvoiceButton_Click(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles InvoiceButton.Click

        For Each row As DataGridViewRow In Me.DataGridView1.SelectedRows

            Dim cust As Customer = TryCast(row.DataBoundItem, Customer)
            If cust IsNot Nothing Then
                cust.SendInvoice()
            End If

        Next

    End Sub

End Class

Public Class Customer

    Private nameValue As String

    Public Sub New(ByVal name As String)
        nameValue = name
    End Sub

    Public Property Name() As String
        Get
            Return nameValue
        End Get
        Set(ByVal value As String)
            nameValue = value
        End Set
    End Property

    Public Sub SendInvoice()
        MsgBox(nameValue & " has been billed.")
    End Sub

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

public class DataGridViewObjectBinding : Form
{
    // These declarations and the Main() and New() methods 
    // below can be replaced with designer-generated code. 
    private Button invoiceButton = new Button();
    private DataGridView dataGridView1 = new DataGridView();

    // Entry point code. 
    [STAThreadAttribute()]
    public static void Main()
    {
        Application.Run(new DataGridViewObjectBinding());
    }

    // Sets up the form.
    public DataGridViewObjectBinding()
    {
        this.dataGridView1.Dock = DockStyle.Fill;
        this.Controls.Add(this.dataGridView1);

        this.invoiceButton.Text = "invoice the selected customers";
        this.invoiceButton.Dock = DockStyle.Top;
        this.invoiceButton.Click += new EventHandler(invoiceButton_Click);
        this.Controls.Add(this.invoiceButton);

        this.Load += new EventHandler(DataGridViewObjectBinding_Load);
        this.Text = "DataGridView collection-binding demo";
    }

    void  DataGridViewObjectBinding_Load(object sender, EventArgs e)
    {
        // Set up a collection of objects for binding.
        System.Collections.ArrayList customers = new System.Collections.ArrayList();
        customers.Add(new Customer("Harry"));
        customers.Add(new Customer("Sally"));
        customers.Add(new Customer("Roy"));
        customers.Add(new Customer("Pris"));

        // Initialize and bind the DataGridView.
        this.dataGridView1.SelectionMode = 
            DataGridViewSelectionMode.FullRowSelect;
        this.dataGridView1.AutoGenerateColumns = true;
        this.dataGridView1.DataSource = customers;
    }

    // Calls the SendInvoice() method for the Customer 
    // object bound to each selected row.
    void invoiceButton_Click(object sender, EventArgs e)
    {
        foreach (DataGridViewRow row in this.dataGridView1.SelectedRows)
        {
            Customer cust = row.DataBoundItem as Customer;
            if (cust != null)
            {
                cust.SendInvoice();
            }
        }
    }
}

public class Customer
{
    private String nameValue;

    public Customer(String name)
    {
        nameValue = name;
    }

    public String Name
    {
        get
        {
            return nameValue;
        }
        set 
        {
            nameValue = value;
        }
    }

    public void SendInvoice()
    {
        MessageBox.Show(nameValue + " has been billed.");
    }
}

코드 컴파일

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

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

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

참고 항목

작업

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

참조

DataGridView

DataGridViewRow

DataGridViewRow.DataBoundItem

기타 리소스

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