none
Dataset, custom collection or generic - what to use when? RRS feed

  • Question

  • Hi all,

     

    I just write .NET code in my spare time and I have no mentor to rely on.  Sometimes this makes this harder to learn.  Writing code is mostly not the most difficult part, one can find plenty of code examples, but making design choices is a different story. 

     

    Currently I am wondering what approach is best to take for my specific situation.  I need a collection to store my objects.  To edit my collection I want databinding to a datagridview.  Most probably I will need special methods to add, remove,... with custom logic, maybe throw exceptions, overloaded methods, ...

     

    I think datasets are not the way to go because I need this custom logic so I would need to write some wrapper around the dataset.  Generics (I never used it, but I know templates in c++)  seems not correct because I do not plan on reusing the logic with other objects.

     

    Please some advice,

     

    thanks,

     

    Jef

    Monday, June 18, 2007 6:32 PM

All replies

  • I would look into using a Generic List (List<T>). I think you will find it quite usefull for the functionality that you described.
    Monday, June 18, 2007 7:07 PM
  • Using a List<T> is generally a good idea, except for one glaring problem:  if you want to be able to sort and filter the data in the DataGridView, you can't, because List<T> doesn't provide the hooks for it.

    You can bind to a List<T>, but List<T> doesn't fully implement IBindingList.  And implementing IBindingList is not trivial:  it's poorly documented, and you'll really need to buy Brian Noyes's book (Data Binding With Windows Forms 2.0) to figure it all out.

    On the other hand, DataGridView and DataTable are meant for one another.  It's easy to generate a DataTable to hold properties of your objects, easy to create a method that fills it, and easy to use the BindingSource's event handlers to keep the DataRows and the underlying objects in sync.

    This does mean that you have two layers of abstraction between the UI and your data, but in practice I haven't found that to be a problem.  And as a free bonus, once you've implemented methods for round-tripping data between your object and the DataRow, you get the WriteXml() and ReadXml() methods, and you're a small amount of code away from being able to persist your objects in a database.
    Monday, June 18, 2007 8:18 PM