방법: Windows Forms DataGridView 행에 바인딩된 개체에 액세스
때로는 비즈니스 개체 컬렉션에 저장된 정보 테이블을 표시하는 것이 유용합니다. DataGridView 컨트롤을 이러한 컬렉션에 바인딩하면 속성이 BrowsableAttribute를 통해 검색 불가능으로 표시되지 않은 경우 각 공용 속성이 해당 열에 표시됩니다. 예를 들어 Customer
개체 컬렉션에는 이름 및 주소와 같은 열이 있습니다.
이러한 개체에 포함된 추가 정보 및 코드에 액세스하려는 경우 행 개체를 통해 접근할 수 있습니다. 다음 코드 예제에서는 사용자가 여러 행을 선택하고 단추를 클릭하여 각 해당 고객에게 송장을 보낼 수 있습니다.
행 바인딩된 개체에 액세스하려면
DataGridViewRow.DataBoundItem 속성을 사용합니다.
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(); } } }
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
예제
전체 코드 예제는 간단한 Customer
구현을 포함하며, 몇 개의 Customer
개체가 포함된 ArrayList에 DataGridView를 바인딩합니다. Form.Load 이벤트 처리기 외부에서는 고객 컬렉션에 액세스할 수 없기 때문에 System.Windows.Forms.Button의 Click 이벤트 처리기는 행을 통해 Customer
개체에 액세스해야 합니다.
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.");
}
}
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
코드 컴파일
이 예제에는 다음 사항이 필요합니다.
- System 및 System.Windows.Forms 어셈블리에 대한 참조
참고 항목
GitHub에서 Microsoft와 공동 작업
이 콘텐츠의 원본은 GitHub에서 찾을 수 있으며, 여기서 문제와 끌어오기 요청을 만들고 검토할 수도 있습니다. 자세한 내용은 참여자 가이드를 참조하세요.
.NET Desktop feedback
피드백
https://aka.ms/ContentUserFeedback
출시 예정: 2024년 내내 콘텐츠에 대한 피드백 메커니즘으로 GitHub 문제를 단계적으로 폐지하고 이를 새로운 피드백 시스템으로 바꿀 예정입니다. 자세한 내용은 다음을 참조하세요.다음에 대한 사용자 의견 제출 및 보기