简体   繁体   中英

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 . How is this possible in vb.net?

The DataGridView has a DataSource.

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

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.

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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