有没有办法在DataRow或DataColumn中存储自定义对象?

时间:2014-11-05 17:41:47

标签: vb.net object datarow datacolumn

有没有办法在DataRow或DataColumn中存储自定义对象?

基本上我正在寻找DataRow或DataColumn的标签属性的等价物。我查看了DataProolles的ExtendedProperties,但是你只能在那里存储字符串。

drNewPathRow = dsOutputGrid.Tables("dtPathElements").Rows.Add()
   elm = pth.Elements(iElements)
   drNewPathRow(0) = elm.Name

    '  drNewPathRow.tag = elm .... I wish!

2 个答案:

答案 0 :(得分:1)

dt.Columns.Add("objCol", GetType(Object))

我不知道我能做到这一点。感谢the_lotus的帮助。

答案 1 :(得分:0)

简单方法是按照@the_lotus的建议创建新列。但是如果你想用艰难的方式那么你需要通过继承TypedTableBase(Of T)类来创建自定义表。您可能需要覆盖/重载/遮蔽更多属性/方法,然后在下面的示例中显示,但是,它应该让您开始。

Public Class StorageTable
    Inherits TypedTableBase(Of StorageRow)

    Protected Overrides Function CreateInstance() As DataTable
        Return New StorageTable()
    End Function

    Protected Overrides Function NewRowFromBuilder(builder As DataRowBuilder) As DataRow
        Return New StorageRow(builder)
    End Function

    Protected Overrides Function GetRowType() As Type
        Return GetType(StorageRow)
    End Function

End Class

Public Class StorageRow
    Inherits DataRow

    Protected Friend Sub New(builder As DataRowBuilder)
        MyBase.New(builder)
    End Sub

    Public Property Tag() As Object

End Class

简单测试:

Using table As New StorageTable()
    table.Columns.Add("Column1", GetType(String))
    table.Rows.Add("value1")
    Dim row As StorageRow = DirectCast(table.Rows(0), StorageRow)
    row.Tag = "value2"
    Debug.WriteLine("Column1={0}, Tag={1}", row.Item(0), row.Tag)
End Using

输出:

  

Column1 = value1,Tag = value2