Custom Object Databinding question

RichardLee

Member
Joined
Dec 29, 2008
Messages
7
Programming Experience
5-10
I have a custom object which I have created lets call it MyObject

The idea behind it is that this object can contain any number of attributes, and I don't know what those attributes may be untill I read them from a database.

So you could have two MyObjects setup to represent User Accounts.

Imagine that the users may have the following details.

User1
UniqueID = 0
Attributes
(0) FirstName = "Bob"
(1) LastName = "Jones"
(2) Sex = "Male"

User2
UniqueID = 1
Attributes
(0) FirstName = "Sarah"
(1) MiddleInitial = "K"
(2) Team = "Unit 1"
(3) DOB = "1/1/1954"

If I where to bind a collection of MyObjects against a DataGridView all that
I would see would be a single column showing the UniqueID's.

But how should I go about exposing each of the attributes as properties that could be bound against the gridview?

so i'd get something like the following appearing in the gridview

[UniqueID], [FirstName], [LastName], [MiddleInitial], [Team], [Sex]
0, Bob, Jones, null, null, Male
1, Sarah, null, K, Unit 1, null

I have seen many examples on the net Like This on how to create a wrapper class where you identify your properties and then you just load the wrapper from the objects you are using.

But in each of the examples I have found, they require you already know the exact number of properties and hardcode this into your wrapper class. But in my system that is not something that I can know before I come to pulling the data out of the database, the data is always subject to change between records, where some objects may have the same attributes, and others may have totally different attributes.

Is there some way of dynamicaly creating a class with any number of properties at runtime? i'm not really sure how best to proceed with this, if anyone has any ideas i'd like to hear them. I'm not event sure this is possible with the gridview so even being told "it can't be done" would be helpful to know.

Here is a rough cut-down example of my classes (not checked to see if this code is working, but should give you an idea what i'm working with).

VB.NET:
  class MyObject
    private _ID as integer
    Private _Attributes As New AttributeCollection

        Public Property UniqueID() As Integer
            Get
                Return _ID
            End Get
            Set(ByVal value As Integer)
                _ID = value
            End Set
        End Property

        Public Property Attributes() As AttributeCollection
            Get
                Return _Attributes
            End Get
            Set(ByVal value As AttributeCollection)
                _Attributes = value
            End Set
        End Property

        Public Sub SetAttribute( _
            ByVal Key As String, _
            Optional ByVal Value As Object = Nothing, _
            Optional ByVal RecordID As Integer = -1 _
        )
            If Attributes.Contains(Key) Then
                Attributes(Key).SetValue = Value
            Else
                Attributes.Add(New Attribute(Key, Value, RecordID))
            End If
        End Sub

  end class

VB.NET:
    Public Class AttributeCollection
        Inherits Collections.ObjectModel.KeyedCollection(Of String, Attribute)

        Protected Overrides Function GetKeyForItem(ByVal item As Attribute) As String
            Return item.Key
        End Function


    End Class

VB.NET:
 Public Class Attribute

        Private _RecordID As Integer 
        Private _Key As String
        Private _Value As String

        Public Property RecordID() As Integer
            Get
                Return _RecordID
            End Get
            Set(ByVal value As Integer)
                _RecordID = value
            End Set
        End Property

        Public Property Key() As String
            Get
                Return _Key
            End Get
            Set(ByVal value As String)
                _Key = value
            End Set
        End Property

        Public Property Value() As String
            Get
                Return _Value
            End Get
            Set(ByVal value As String)
                Me.SetValue = value
            End Set
        End Property

        Public WriteOnly Property SetValue() As Object
            Set(ByVal value As Object)
                If IsNothing(value) Then
                    _Value = Nothing
                    Exit Property
                End If
                If value.GetType.ToString.Contains("DBNull") Then
                    _Value = Nothing
                Else
                    _Value = value
                End If
            End Set
        End Property

        Public Sub New( _
            Optional ByVal Key As String = Nothing, _
            Optional ByVal Value As Object = Nothing, _
            Optional ByVal RecordID As Integer = -1 _
        )
            With Me
                .RecordID = RecordID
                .Key = Key
                .SetValue = Value
            End With
        End Sub

    End Class
 
Last edited:
That sounds like a really retarded way to organise a database. Each record in a table can have a varying number of, and names of columns?

Nonetheless, the datagridview is capable of autogenerating columns based on what it finds, I've just never really used it in that way. If you make a dataadapter to "select * from a_table" into a normal, untyped datatable, then the datatable acquires a number of columns and the datagridview renders them automatically and varying..

However, it really sounds like youre actually merely wanting to pivot a name=value list which I'd recommend you get the database to do (using a database that supports pivoting easily). I can't think of an easy way to have an object that has a varying number of named, typed, properties unless reflection will allow you to add and remove properties and define the code for how they behave.

I actually think three's a flaw in your data modelling somewhere, and youre trying to make a logical system out of some inherently illogical thought process
 
You think its retarded? What about the the following

<users>

<user id=0>
<FirstName>Bob</FirstName>
<LastName>Jones</LastName>
<Sex>Male</Sex>
</user>

<user id=1>
<FirstName>Sarah</FirstName>
<MiddleInital>K</MiddleInitial>
<Team>Unit 1</Team>
<DOB>1/1/1954</DOB>
</user>

</users>

Looks like xml to me, Thats pretty much the same thing that I am trying to get going with my system (however Xml is overkill for what I want to do, so I just wanted a cut down set of classes to work with).

Maybe you think that the concept behind Xml is retarded as well?

Anyway thanks for replying all the same, even if you want to insult me at the same time.

Will take a look at the pivot idea and see what I can make out of it. I agree that the DB should be doing as much of the work as possible.
 
Your first post reads like you have everything in the world stored in one table; that is retarded. Here youre describing people, one subset of Everything, and though you have "lots of variable properties" you actually don't.. You merely have a lot of properties related to a person, and some of those can be null. Allow me to rewrite your XML to illustrate my point:

VB.NET:
<users>

<user id=0>
<FirstName>Bob</FirstName>
<LastName>Jones</LastName>
<Sex>Male</Sex>
<MiddleInital/>
<Team/>
<DOB/>
</user>

<user id=1>
<FirstName>Sarah</FirstName>
<MiddleInital>K</MiddleInitial>
<Team>Unit 1</Team>
<DOB>1/1/1954</DOB>
<LastName/>
<Sex/>
</user>

</users>

Ergo, you can completely define every property you wish to express and work with, about a person in one design-time coded interface. Why are you breaking heads trying to make it so that the end user can add anything they like to your "list of attributes a person may possess" - youre not going to be able to write code that uses those attributes if they add them after you code the app.

Actually, microsoft created something that could do this: it's called a database, so all you have to do is re-create Access and all your users have to do is learn how to create a database in your version of Access. i.e. they must become developers. But then we come to the realisation that there is no point reinventing Microsoft Access because Microsoft Access already does a pretty good job of it, and users are never going to become developers because if they were mentally equipped to do so, you and I would be out of a job!

As a developer, you provide targeted functionality to users by limiting the expressivity therein. You hide detail and impose limits. Providing users with a massively flexible system means that they won't use it, because youre not appreciating the difference between them and yourself.

In this case, your problem comes to one of O/R mapping and you can seek out ways of storing XML, or database columns and working with the data no problem. You put a lot more effort in as a developer and the users will have a hugely flexible system at the other end, but it'll cost a lot and be of no use because the users won't be able to cope with it. Right now, I'd decide if you want to go XML or classic DB; it really depends on what other donkeywork you'd like the DB to do and whetehr e.g. oracle financial and analytical function provisions are appealing to you. Your question thus grows massively and it'll be difficult to find someone to commit lengthy posts on a forum to give worthwhile advice. If all you want to do is edit a column of rows as if they were a row of columns, that's a pivot
 
Last edited:
Who said I wanted to make a system that was logical? You shouldn't jump to conclusions :p

I never said this was for any end users to play with (another assumption of yours). I only wanted it to be flexible enough for me to use, no one else.

It's just a code example I am playing with, its not meant for general release to anyone in particular, I'm just messing around, seeing how it works with databound controls and seeing what lessons I can learn from it.

I hit the problem as described above and wanted to see what people could come up with. I know the usual alternatives and while a relational db is the easier solution to go with, i'm not really interested in doing things the easy way. I wanted to try and look at it from a different position, just to see if there is anything I can learn from it.

If you want to look at it another way its an attempt to shoehorn a basic level of object oriented support into a relational database, not something which makes a whole load of sense in the first place. Why not just use a true object oriented database in the first place I hear you say, and of course you would be right, that would also be more logical. But I'm forbidden to use OO db's its against my religion apparently.

Maybe it is possible to create an object with X number of properties at runtime? thats at the heart of what I wanted to know. These class files are just my attempt to recreate that type of problem.

Reflection sounds interesting but i've never used it before so wouldn't know how or where to get started with it.

Anyway thanks for the advice.
 
Who said I wanted to make a system that was logical? You shouldn't jump to conclusions :p
Youre using a computer. Forgive my drawing the conclusion that you wanted to create a logical system.

I never said this was for any end users to play with (another assumption of yours). I only wanted it to be flexible enough for me to use, no one else.
OK, well it's even simpler to answer your question then: Visual Studio. Microsoft Access. <insert development language, sql tool or rdbms of your choice>
All great, super flexible systems.. Immensely powerful too, and can cope with all manner of shapes of data

It's just a code example I am playing with, its not meant for general release to anyone in particular, I'm just messing around, seeing how it works with databound controls and seeing what lessons I can learn from it.
OK, well.. Lesson 1 I guess would be "when using a structured, logical language and describing the rules in advance of the application of them, you must know the logics of how and what you will apply them to"

i.e. It's not possible to write a system that will know how to solve every problem you havent come across, or give you every item of data it doesnt have.


If you want to look at it another way its an attempt to shoehorn a basic level of object oriented support into a relational database,
This is more commonly know as the object-relational impedance mismatch. There's quite an extensive wiki article about it that would be a good starting place

Maybe it is possible to create an object with X number of properties at runtime? thats at the heart of what I wanted to know. These class files are just my attempt to recreate that type of problem.
It depends what you mean by "property".

One could argue that a Dictionary(Of String, Object) satisfies your requirement. You can call myDict("Age") and get an Integer 27 out of it, or myDict("Address") and get a custom AddressInfo class out of it. You can even ask it for a set of all its keys, or all its values so you know what is in it and what you can query..

But how does it help? So you let the user (you) add a proeprty of name asdjhfjsdhflkjs and a value of 231490203845. What significance does it have? How will you code your app to make use of this information? If youre only shooing the information back and forth between a user and a disk, then what have you achieved beyond an incredibly simple database, text document, etc?

Computer programs typically turn data into information by means of interpretation and manipulation, but if youre allowing a generic anything to be entered and retrieved, I struggle to see how you can add value to this data

Reflection sounds interesting but i've never used it before so wouldn't know how or where to get started with it.
It's basically introspection, in a programmatic sense. Bearing in mind that a computer program is usually some sum of its component parts, what you can look at is hence limited. I'm not sure what you seek, let alone whether you'll find it upon Reflection
 
Youre using a computer. Forgive my drawing the conclusion that you wanted to create a logical system.

Your forgiven, I was only joking. (is there even such a thing as an illogical programming language?)

OK, well it's even simpler to answer your question then: Visual Studio. Microsoft Access. <insert development language, sql tool or rdbms of your choice>
All great, super flexible systems.. Immensely powerful too, and can cope with all manner of shapes of data

Yes but as I said its just a programming exercise, how do I learn anything if I just skip doing the programming part, because some other software already exists and I just go and buy that in instead.

I know of the alternatives, thats not the point, I just want to try out a few things myself, just to get my head around the concepts, thats all.

One could argue that a Dictionary(Of String, Object) satisfies your requirement. You can call myDict("Age") and get an Integer 27 out of it, or myDict("Address") and get a custom AddressInfo class out of it. You can even ask it for a set of all its keys, or all its values so you know what is in it and what you can query..

Maybe your right, perhaps I am over complicating this thing.

But in the mean time I looked into your idea of pivot tables. Something which I had already done before coming to this forum, but your prompting made me take another look at it.

I found a few examples, and after modifying it to suit my needs, managed to get SQL server to create a dataset for me. With all the attributes output as columns, substituting null's for any attributes the other records don't hold. Thats exactly what I wanted to achieve. So this discussion has been useful to me.

Had to also incorporate some dynamic sql as well, which was the point of this exercise, to learn something new and useful.
 
Yes but as I said its just a programming exercise, how do I learn anything if I just skip doing the programming part, because some other software already exists and I just go and buy that in instead.
I take a somewhat more "commercenary" approach, I think; if something better than I can do for less than it would cost me to find out how to do, is available I generally use it. My car for example. I might onhe day make a kit car, but I probably won't fabricate all the parts myself :)

I know of the alternatives, thats not the point, I just want to try out a few things myself, just to get my head around the concepts, thats all.
Well, you'd probably have to write a new programming language if you wanted to do away with imposition of order, type safety, compile time checks etc.. It would be illogical to use a language that has adopted certain concepts as it's keystones if you were seeking to create a system that deliberately dispenses with those same keystones.. Much like if you had a requirement that a wall be flexible and opaque, starting with glass as a raw material will unnecessarily hinder your progress :)



Had to also incorporate some dynamic sql as well, which was the point of this exercise, to learn something new and useful.
Don't forget to parameterize your queries ;) See the PQ link in my signature for more info
 

Latest posts

Back
Top