Reputation: 10345
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.
Upvotes: 1
Views: 652
Reputation: 125197
You can use either of these options:
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
Upvotes: 2