This question applies to VB.net and C# so I posted it here in the hope I will get more answers. However, the code will be presented in VB.net. Feel free to respond in C#
The program bellow trhows an error in the line "mTable2 = mTable.Copy". The error is: "Unable to cast object of type 'System.Data.DataTable' to type 'InherintanceQuestion.InheritedTable". This is because mTables is an instance of the InheritedTable class which inherits a DataTable and mTable is a DataTable. So, is there any way I can create the mTable2 to the mTable.copy to the mTable.
VB.NET
PublicClass Form1
PrivateSub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim mTable AsNew DataTable
Dim mTable2 AsNew InheritedTable
mTable.Columns.Add("Col1", System.Type.GetType("System.String"))
mTable.Columns.Add("Col2", System.Type.GetType("System.String"))
Dim Row As DataRow = mTable.NewRow
Row(0) = "A" : Row(1) = "B" : mTable.Rows.Add(Row)
Row = mTable.NewRow
Row(0) = "C" : Row(1) = "D" : mTable.Rows.Add(Row)
mTable2 = CType(mTable.Clone, InheritedTable).Copy 'THE ERROR OCCURS HEREEndSubEndClassPublicClass InheritedTable
Inherits System.Data.DataTable
PrivateSub DoSomething()
'Any code.EndSubEndClass
1 Answer
Know the answer? Post it. Somebody with the same question will find it here.
PJ MartinsRank #2,548 · 548 reputationPosted May 26, 2010, 7:09 AM EDT
0
You can only cast objects down to their base types, you would have to add a method to your InheritedTable class to copy the columns and rows from an existing table. Something like:
Public Sub CopyFrom(ByVal dt as DataTable)
Me.TableName = dt.TableName
For Each col as DataColumn in dt.Columns
Me.Columns.Add(col.ColumnName, col.DataType)
Next
For Each row as DataRow in dt.Rows
Me.ImportRow(row)
Next
End Sub
PJ MartinsRank #2,548 · 548 reputationPosted May 26, 2010, 7:09 AM EDT
Public Sub CopyFrom(ByVal dt as DataTable)
Me.TableName = dt.TableName
For Each col as DataColumn in dt.Columns
Me.Columns.Add(col.ColumnName, col.DataType)
Next
For Each row as DataRow in dt.Rows
Me.ImportRow(row)
Next
End Sub