Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/vb.net/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Vb.net 如何合并2个数据属性并在DataGridView的单个列中显示它们?_Vb.net_Winforms_Datagridview - Fatal编程技术网

Vb.net 如何合并2个数据属性并在DataGridView的单个列中显示它们?

Vb.net 如何合并2个数据属性并在DataGridView的单个列中显示它们?,vb.net,winforms,datagridview,Vb.net,Winforms,Datagridview,我想在DataGridView中的一列中合并并显示两个数据字段。在vb.net中,这是如何实现的 DataGridView有一个数据源。您可以使用以下任一选项: 为DataTable创建计算列 为类创建只读属性 处理DataGridView的CellFormatting事件 为DataTable创建计算列 如果数据字段属于数据表,则可以将计算的数据列添加到数据表,并将其属性设置为基于这两列返回所需值 table.Columns.Add("DisplayName", GetType(Strin

我想在
DataGridView
中的一列中合并并显示两个数据字段。在vb.net中,这是如何实现的


DataGridView
有一个数据源。

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

  • 为DataTable创建计算列
  • 为类创建只读属性
  • 处理DataGridView的CellFormatting事件
为DataTable创建计算列

如果数据字段属于
数据表
,则可以将计算的
数据列
添加到
数据表
,并将其属性设置为基于这两列返回所需值

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
的事件,并基于这两个字段将
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

这篇帖子似乎回答了你的问题,如果你接受这个答案或者如果你对答案有任何疑问,请告诉我:)