如何合并2个数据属性并将其显示在DataGridView的单列中? [英] How can I merge 2 data properties and show them in a single Column of DataGridView?

查看:497
本文介绍了如何合并2个数据属性并将其显示在DataGridView的单列中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 DataGridView 中的1列中合并并显示2个数据字段。如何在vb.net中实现?

I want to merge and display 2 data fields in 1 column in the DataGridView. How is this possible in vb.net?

DataGridView 有一个DataSource。

The DataGridView has a DataSource.

推荐答案

您可以使用以下任一选项:

You can use either of these options:


  • 计算列DataTable

  • 为Class创建只读属性

  • 处理DataGridView的CellFormatting事件

为DataTable创建计算列

Creating a computed Column for DataTable

如果数据字段属于 DataTable ,您可以将 DataColumn 添加到您的 DataTable 中并设置其 表达式 属性,以根据这两列返回所需的值。

If data fields belongs to a DataTable you can add a computed DataColumn to your DataTable and set its Expression property to return desired value based on those two columns.

table.Columns.Add("DisplayName", GetType(String), "FirstName + ' ' + LastName")

创建只读Prop如果数据字段属于一个纯模型类,则可以添加一个只读属性,该属性在getter中,根据这些属性返回所需的值2

属性。

Public Class Person
    Public Property FirstName As String
    Public Property LastName As String
    Public ReadOnly Property DisplayName As String
        Get
            Return String.Format("{0} {1}", FirstName, LastName)
        End Get
    End Property
End Class

使用DataGridView的CellFormatting事件

作为所有情况的一般解决方案,您可以使用 CellFormatting 事件 DataGridView 和根据这两个字段将 e.Value 设置为所需的值。

As a general solution for all cases, you can use CellFormatting event of DataGridView and set e.Value to desired value based on those two fields.

Private Sub DataGridView1_CellFormatting(sender As Object,  _
    e As DataGridViewCellFormattingEventArgs Handles DataGridView1.CellFormatting
    ' For example you want to do it for 3rd column
    If e.ColumnIndex = 2 AndAlso e.RowIndex >= 0 Then   
        Dim row = Me.DataGridView1.Rows(e.RowIndex)
        'If DataSource is a DataTable, DataBoundItem is DataRowView
        Dim data = DirectCast(row.DataBoundItem, Person)
        e.Value = String.Format("{0} {1}", data.FirstName, data.LastName)
    End If
End Sub

这篇关于如何合并2个数据属性并将其显示在DataGridView的单列中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆