![](/img/trans.png)
[英]How can i bind a generic List of custom classes to a datagridview and only show specific properties in VB.NET?
[英]How can I merge 2 data properties and show them in a single Column of DataGridView?
我想合并并在DataGridView
1列中显示2个数据字段。 在vb.net中怎么可能?
DataGridView
有一个数据源。
您可以使用以下任一选项:
为数据表创建计算列
如果数据字段属于DataTable
,则可以将计算DataColumn
添加到DataTable
,并将其Expression
属性设置为基于这两列返回所需的值。
table.Columns.Add("DisplayName", GetType(String), "FirstName + ' ' + LastName")
为类创建一个只读属性
如果数据字段属于普通模型类,则可以添加一个只读属性,该属性在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
使用DataGridView的CellFormatting事件
作为所有情况的通用解决方案,可以使用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.