问题
Is it possible to create a new DataRow object and add columns to it at runtime?
// How can I specify column names for this data row object?
DataRow row = new DataRow();
回答1:
I don't think you can add columns to a datarow, but you certainly can to a datatable. Here's some code to do this for VB:
Enum enumType
StringType = 1
BooleanType = 2
DateTimeType = 3
DecimalType = 4
DoubleType = 5
IntegerType = 6
CharType = 7
End Enum
Private Shared ReadOnly Property ColumnDataType(ByVal ThisDataType As enumType) As String
Get
'DataType values supported are:
'System.Byte, System.Char, System.DateTime, System.Decimal, System.Double, System.Int16, System.Int32, System.Int64,
'System.SByte, System.Single
Select Case ThisDataType
Case enumType.BooleanType
Return "System.Boolean"
Case enumType.DateTimeType
Return "System.DateTime"
Case enumType.DecimalType
Return "System.Decimal"
Case enumType.DoubleType
Return "System.Double"
Case enumType.IntegerType
Return "System.Int32"
Case enumType.StringType
Return "System.String"
Case enumType.CharType
Return "System.Char"
Case Else
cnst.ErrorDisplay("No such data type as " & ThisDataType.ToString)
Return Nothing
End Select
End Get
End Property
Public Shared Sub AddColumn(ByRef dt As DataTable, ByVal ColumnName As String, ByVal ThisDataType As enumType)
Dim dc As DataColumn = New DataColumn(ColumnName)
dc.DataType = System.Type.GetType(ColumnDataType(ThisDataType))
dt.Columns.Add(dc)
End Sub
The code uses an enumeration. I got some of the ideas from this page. The idea is that you can call the AddColumn method to add any column that you like to the datatable.
回答2:
No. A DataRow is designed to be a child of a DataTable, which has the accessors needed to add columns. If you could manipulate DataRows directly, it would be possible to create a "jagged table" with rows having different column counts/orders. This is generally a bad thing, so it's just not done.
If you want to add a column to your DataRow, add your Row to a DataTable, add a column to that DataTable, then look at your DataRow again.
来源:https://stackoverflow.com/questions/10108080/add-columns-to-new-datarow