如何:访问绑定到 Windows 窗体 DataGridView 行的对象

      有时,显示业务对象集合中存储的信息的表很有用。将 DataGridView 控件绑定到此类集合时,每个公共属性都将在它自己的列中显示,除非该属性已用 BrowsableAttribute 标记为不可浏览。例如,Customer 对象的集合将具有如“姓名”和“地址”等列。

如果这些对象包含您希望访问的附加信息和代码,则可以通过行对象来实现。在下面的代码示例中,用户可以选择多行并单击一个按钮将发票发送给每个对应客户。

访问行绑定对象

  • 使用 System.Windows.Forms.DataGridViewRow.DataBoundItem 属性。

    Visual Basic
    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 Not cust Is 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();
            }
        }
    }
    
    void invoiceButton_Click(Object sender, EventArgs e)
    {
        for (int iCtr = 0; iCtr < this.dataGridView1.get_SelectedRows().
            get_Count(); iCtr++) {
            DataGridViewRow row = this.dataGridView1.get_SelectedRows().
                get_Item(iCtr);
            Customer cust =(Customer)row.get_DataBoundItem();
            if (cust != null) {
                cust.SendInvoice();
            }
        }
    } //invoiceButton_Click
    

示例

完整的代码示例包括一个简单的 Customer 实现,并将 DataGridView 绑定到一个包含几个 Customer 对象的 ArrayList

Note注意

因为在 System.Windows.Forms.Form.Load 事件处理程序之外无法访问客户集合,所以 System.Windows.Forms.ButtonClick 事件处理程序必须通过行访问 Customer 对象。

Visual Basic
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 Not cust Is 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.");
    }
}
import System.*;
import System.Windows.Forms.*;

public class DataGridViewObjectBinding extends 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. 
    public static void main(String[] args)
    {
        Application.Run(new DataGridViewObjectBinding());
    } //main

    // Sets up the form.
    public DataGridViewObjectBinding()
    {
        this.dataGridView1.set_Dock(DockStyle.Fill);
        this.get_Controls().Add(this.dataGridView1);
        this.invoiceButton.set_Text("invoice the selected customers");
        this.invoiceButton.set_Dock(DockStyle.Top);
        this.invoiceButton.add_Click(new EventHandler(invoiceButton_Click));
        this.get_Controls().Add(this.invoiceButton);
        this.add_Load(new EventHandler(DataGridViewObjectBinding_Load));
    } //DataGridViewObjectBinding

    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.set_SelectionMode(
            DataGridViewSelectionMode.FullRowSelect);
        this.dataGridView1.set_AutoGenerateColumns(true);
        this.dataGridView1.set_DataSource(customers);
    } //DataGridViewObjectBinding_Load

    // Calls the SendInvoice() method for the Customer 
    // object bound to each selected row.
    void invoiceButton_Click(Object sender, EventArgs e)
    {
        for (int iCtr = 0; iCtr < this.dataGridView1.get_SelectedRows().
            get_Count(); iCtr++) {
            DataGridViewRow row = this.dataGridView1.get_SelectedRows().
                get_Item(iCtr);
            Customer cust =(Customer)row.get_DataBoundItem();
            if (cust != null) {
                cust.SendInvoice();
            }
        }
    } //invoiceButton_Click
} //DataGridViewObjectBinding

public class Customer
{
    private String nameValue;

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

    /** @property 
     */
    public String get_Name()
    {
        return nameValue;
    }//get_Name

    /** @property 
     */
    public void set_Name(String value)
    {
        nameValue = value;
    }//set_Name

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

编译代码

此代码需要:

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值