.NET 2.0: DataGridView and DataSource



  • Hello everyone,

    I'm new to .NET and decided to give it a try for a small, non-critical app. Basically, it's a configuration dialog with several text fields which are hooked to a simple storage object via .NET's neat DataBinding mechanism like that:

    exampleTextBox.DataBindings.Add("Text", Config, "exampleProperty");

    The Config object is finally serialized to an XML file using the nifty XmlSerializer. Pretty cool stuff so far!
    Now I also need a DataGridView with two columns and a variable amount of rows (well, what else would you need DataGridView for, anyway). Obviously, hooking a DataGridView to a storage object isn't as trivial as it is with a text box. I realize there is a DataSource property which is supposed to be used for that matter, but still, I couldn't find a way to set it to e. g. an ArrayList containing structs with simple string members corresponding to the DataGridView's columns -- which is, of course, nothing to be surprised at: Why should the DataGridView know what kind of model I use to store its data?

    Since I noticed many .NET people are reading these forums, I was hoping someone could shed some light on this issue for me!

    0



  • If you want to bind your DataGridView to a custom collection, you should inherit from CollectionBase.  I can't remember exactly what interfaces are needed for binding, but CollectionBase implements IList, ICollection, & IEnumerable.

    Here is an article I found that you might find useful http://www.ondotnet.com/pub/a/dotnet/2003/06/02/collectionbase.html




  • Thanks for your advice! I found inheriting from CollectionBase was too bothersome, so I discovered another way: Inheriting from BindingList, which is a bindable generic list -- bingo! Now I can use the visual designer to connect properties of my customly defined item classes to the columns of my DataGridView. Hooray!

    0


Log in to reply