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).
Who is Participating?
Miguel OzConnect With a Mentor Software EngineerCommented:
The reason you can't bind a dictionary to a DataGridView is that  the DataGridView.DataSource needs an object that implements IList, IListSource, thus generic list is needed
For a sample, check:
An alternative using a derived dictionary is here:
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.
deleydAuthor Commented:
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?
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.