简体   繁体   English

如何合并2个数据属性并将其显示在DataGridView的单个列中?

[英]How can I merge 2 data properties and show them in a single Column of DataGridView?

I want to merge and display 2 data fields in 1 column in the DataGridView . 我想合并并在DataGridView 1列中显示2个数据字段。 How is this possible in vb.net? 在vb.net中怎么可能?

The DataGridView has a DataSource. DataGridView有一个数据源。

You can use either of these options: 您可以使用以下任一选项:

  • Creating a computed Column for DataTable 为数据表创建计算列
  • Creating a read-only Property for Class 为类创建一个只读属性
  • Handling CellFormatting event of DataGridView 处理DataGridView的CellFormatting事件

Creating a computed Column for 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. 如果数据字段属于DataTable ,则可以将计算DataColumn添加到DataTable ,并将其Expression属性设置为基于这两列返回所需的值。

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

Creating a read-only Property for Class 为类创建一个只读属性

If data fields belongs to a plain model class you can add a read only property which in the getter, return desired value based on those 2 properties. 如果数据字段属于普通模型类,则可以添加一个只读属性,该属性在getter中将基于这两个属性返回所需的值。

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

Using CellFormatting event of DataGridView 使用DataGridView的CellFormatting事件

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. 作为所有情况的通用解决方案,可以使用DataGridView CellFormatting事件,并根据这两个字段将e.Value设置为所需值。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM