Can't store custom objects in a DataTable?

  • Thread starter Thread starter Lucvdv
  • Start date Start date
L

Lucvdv

[Using VB.Net 2003]

When filling a DataTable, I'm feeding instances of a custom class into one
of its columns, the way you would do with a ListBox for example.

My problem is that even though it accepts data of generic type "object", it
only seems to store a string representation in the DataTable.

"SettingItem" below is a custom class.

With a ListBox this works:

Dim lstTest As New ListBox
Dim x As New SettingItem
lstTest.Items.Add(x)
Debug.WriteLine(lstTest.Items(0).GetType)

It prints "ApplicatiunName.SettingItem".
Later, you can access the full selected SettingItem object in the listbox's
events. You control what is displayed in the listbox by overriding the
ToString method of whatever class you fill it with.


The Item property of a DataRow in a DataTable has "object" as type, so I
expected it to work the same way.

Dim dtSettings As New DataTable("Settings")
Dim dr As DataRow = dtSettings.NewRow
Dim ds As New SettingItem
...
dr.Item("Value") = ds
dtSettings.Rows.Add(dr)

Debug.WriteLine(dtSettings.Rows(0).Item("Value").GetType)

prints "System.String".


The DataTable is used as data source for a DataGrid control, and I created
a custom column editor derived from DataGridColumnStyle to edit the values.
There, the GetColumnValueAtRow method still returns an "object", and I need
it to give access to the original object that was stored in the DataTable.

Can this be done, or is there a simple workaround?
 
hi,
i don't have the complete answer to your question, but it may help if i
point out that it is a feature of the Control that supports databinding to
objects. the same mechanism isn't included with the value in a dataTable
cell.

if i were you, i would try to bind the datagrid directly to a collection
class of your complex objects, and not try to mix datatable representations
of the data with the complex objects themselves.

good luck
tim
 
I don't think you will be able to do it.
Perhaps you might create a hashtable where you associate a row with an
object?
 
Dim dtSettings As New DataTable("Settings")
Dim dr As DataRow = dtSettings.NewRow
Dim ds As New SettingItem
...
dr.Item("Value") = ds
dtSettings.Rows.Add(dr)

Debug.WriteLine(dtSettings.Rows(0).Item("Value").GetType)

prints "System.String".

Found it:

dtSettings.Columns("Value").DataType = _
System.Type.GetType("ApplicationName.SettingItem")

and the correct type comes through all the way to GetColumnValueAtRow in
the DataGridColumnStyle-derived class.
 
Back
Top