Category / Section
How to bind dictionary to column in WinForms DataGrid (SfDataGrid)?
1 min read
WinForms DataGrid (SfDataGrid) provides support to bind the Dictionary with SfDataGrid.Columns.
In the below code snippet marks dictionary bound to GridColumns by specifying the property name and key to MappingName of GridColumn.
sfDataGrid.AutoGenerateColumns = false; sfDataGrid.DataSource = new ViewModel().StudentDetails; sfDataGrid.Columns.Add(new GridTextColumn() { MappingName = "StudentID", HeaderText = "Student ID" }); sfDataGrid.Columns.Add(new GridTextColumn() { MappingName = "StudentName", HeaderText = "Student Name" }); sfDataGrid.Columns.Add(new GridTextColumn() { MappingName = "Major", HeaderText = "Major" }); sfDataGrid.Columns.Add(new GridTextColumn() { MappingName = "Marks[Subject1]", HeaderText = "Marks[Subject1]" }); sfDataGrid.Columns.Add(new GridTextColumn() { MappingName = "Marks[Subject2]", HeaderText = "Marks[Subject2]" });
Below is the sample code snippet where Model is added with Dictionary property type (Marks property). You can bind value from dictionary by mapping its key with column.
var dictionary = new Dictionary<string, int>(); dictionary.Add("Subject1", 85); dictionary.Add("Subject2", 96); studentDetails = new ObservableCollection<Model>(); studentDetails.Add(new Model() { StudentID = 101, StudentName = "Joseph", Age = 25, Major = "Psychology", Marks = dictionary, });
The following screenshot shows bind the Dictionary with a column,
Take a moment to peruse the WinForms DataGrid – Data Binding documentation, where you can find about data binding with code examples.