Link to home
Start Free TrialLog in
Avatar of deleyd
deleydFlag for United States of America

asked on

Binding a Dictionary to a DataGridView?

I'm trying to make a simple test application that will display the contents of a Dictionary in a DataGridView. Not sure if it's possible or what I need to add.

Say I have a simple class to store some data:
    class Myclass
    {
        private string fn;
        private string comment;
        public string Fn
        {
          get { return fn; }
          set { fn = value; }
        }
        public string Comment
        {
          get { return comment; }
          set { comment = value; }
        }
    }

Open in new window

(I think there's a shorter method of declaring these get/set pairs but I forget how it's done. Do you know how to shorten this?)

And then I have a dictionary containing some members of my class
            Dictionary<string, Myclass> mydic = new Dictionary<string, Myclass>();
            var d1 = new Myclass();
            d1.Fn = "Hello World";
            d1.Comment = "A Comment #1";
            mydic.Add("key1", d1);

Open in new window

Now I think I want to bind this dictionary to my DataGridView so I can see what's in the dictionary, but I'm not sure how to do this in Visual Studio (or manually for that matter).
Avatar of dimaj
dimaj
Flag of United States of America image

Why use a dictionary? Why don't you just use a List<Myclass>. Then, do a data binding that would bind your list to your data grid.

If not, you can always resort to using Linq.
I think, You must create list grid.DataSource = new List<Myclass>(mydic.Values) and bind datasource every time dictionary changes or every time you want to see dictionary.
Avatar of deleyd

ASKER

OK so no direct binding to Dictionary? A dictionary (hash table) would be the ideal for storing this data, since it would allow quick random access to records by key. But to display the records,? Any samples of code showing how to display all the data records?
ASKER CERTIFIED SOLUTION
Avatar of Miguel Oz
Miguel Oz
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial