'C# How to display a ConcurrentDictionary in a DataGridView (WinForms)

I have an object "User"

public class User
    {
        public string UserName { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string LastRequestId { get; set; }
    }

In the main program I have a ConcurrentDictionary "UserList" (read/write by multiple threads)

private ConcurrentDictionary<string, User> UserList;

Is there a way to display the ConcurrentDictionary in a DataGridView?

-------------------------------------------------------
| Username | First Name | Last Name | Last Request Id |
-------------------------------------------------------
| User_1   | John       | Smith     | REQ_000123      |
-------------------------------------------------------
| User_2   | Jane       | Doe       | REQ_000124      |
-------------------------------------------------------
| User_3   | Will       | Iam       | REQ_000125      |
-------------------------------------------------------
| User_4   | Robert     | New       | REQ_000126      |
-------------------------------------------------------

The list should display real time data



Solution 1:[1]

CurrentDictionary doesn't support display directly in a UI because it is not an IList or an IListSource. So you will need to create an object that is representative of your Dictionary's contents that implements one of those interfaces, assign it to the DataGridView.DataSource, and update that list from the UI thread.

One possible approach for this is to add a Timer to your Form that fires periodically (say once a second or so), and compares the contents of your dictionary to the contents of the DataGridView.DataSource and synchronizes them. (Removes elements that have been removed, adds elements that have been added, etc). This approach won't scale well at all if you have lots of entries being added very quickly, but that seems unlikely.

Here's an example using a regular Dictionary<TKey,TValue> DataGridView bound to a Dictionary, which describes several ways to convert a dictionary type to a BindingList<T>.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1