Data Binding
This section explains the purpose of DataBinding in SfDataGrid, different properties and event available to bind data to SfDataGrid.
Overview
DataBinding is the master feature of the SfDataGrid. The SfDataGrid is bound to an external data source to display the data. SfDataGrid supports the data sources such as List, Observable Collection, and so on.
The following is the list of properties that supports to Data Binding in various ways.
SfDataGrid.ItemsSource: This Dependency property helps to bind the SfDataGrid with the collection of objects
SfDataGrid.IsDynamicItemsSource: This Dependency property helps to check whether the bounded items source is dynamic or not. Set this property when you load empty collection.
SfDataGrid.SourceType: This Dependency property decides the type of source collection that is bounded to ItemsSource. This helps to define the SourceType in the following use cases,
-
When you use Inheritance to make collection using derived class and set SourceType as type of Base Class, the Base class property is displayed in the SfDataGrid.
-
When you use dynamic collection and set type as particular user defined class, then the properties are displayed in the SfDataGrid.
NOTE
It is always not necessary to set SourceType and IsDynamicItemsSource properties.
The following event is associated with Data Binding.
ItemsSourceChanged Event
This event rises when the data source for the SfDataGrid is changed by using the ItemsSource property. This event receives two arguments namely sender that handles SfDataGrid and GridItemsSourceChangedEventArgs as objects.
The GridItemsSourceChangedEventArgs object contains the following properties:
- OldItemsSource: Gets the value of old data source.
- NewItemsSource: Gets the value of new data source.
You can use this event when you want to wire CollectionView related event. During this event ItemsSourceChanged view is populated. You can wire CollectionChanged and SourceCollectionChanged events also.
The following sections explain you how to bind different ItemsSource to SfDataGrid.
View
SfDataGrid has the View property of type ICollectionViewAdv interface that implements ICollectionView interface. View is responsible for maintain and manipulation data and other advanced operations like Sorting, Grouping, Filtering and etc. When you bind Collection to ItemsSource property of SfDataGrid, then View is created and maintains the operations on Data such as Grouping, Filtering, Sorting, Insert, Delete, and Modification. Following are some important properties that are used for various purposes.
NOTE
SfDataGrid creates different types of views derived from ICollectionViewAdv interface based on ItemsSource.
Property | Type | Description |
---|---|---|
Records | IRecordsList | Maintains the Records that are displayed in View when SfDataGrid is not Grouped. |
TopLevelGroup | TopLevelGroup | Maintains the Group information when SfDataGrid is Grouped. |
TopLevelGroup.DisplayElements | GroupDisplayElements | Maintains the Records and Group information that are displayed in View when SfDataGrid is Grouped. |
Filter | Predicate < object > | Get or sets the method that determines the data is suitable to be displayed in View. |
FilterPredicates | ObservableCollection < IFilterDefinition > | Maintains the FilterPredicates that are created while filtering using Filtering UI. |
Groups | ReadOnlyObservableCollection < object > | Maintains the top-level group information. It returns null value when there no groups. |
GroupDescriptions | ObservableCollection < GroupDescription > | Maintains the GroupDescription collection information. It describes how the items in the collection are grouped in the view. |
SortDescriptions | SortDescriptionCollection | Maintains the SortDescription collection information. It describes how the items in the collection are sort in the view. |
SourceCollection | IEnumerable | Maintains the underlying source collection. |
TableSummaryRows | ObservableCollection < ISummaryRow > | Maintains the TableSummaryRows collection information. |
SummaryRows | ObservableCollection < ISummaryRow > | Maintains the SummaryRows collection information. |
CaptionSummaryRows | ISummaryRow | Maintains the CaptionSummaryRow information. |
The following events are associated with View.
RecordPropertyChanged
This event is raised when the DataModel property value is changed, for example when the DataModel implements the INotifyPropertyChanged interface. The event receives two arguments namely sender that handles the DataModel and PropertyChangedEventArgs as an object.
PropertyChangedEventArgs has the following property,
PropertyName – It denotes the PropertyName of the changed value.
CollectionChanged
This event is raised whenever there is some change in Records / DisplayElements collection. The event receives two arguments namely sender that handles View object and NotifyCollectionChangedEventArgs as object.
NotifyCollectionChangedEventArgs has the following properties,
Action - It contains the current action. (i.e) Add, Remove, Move, Replace, Reset.
NewItems-It contains the list of new items involved in the change.
OldItems-It contains the list of old items affected by the Action.
NewStartingIndex-It contains the index where the change occurs.
OldStartingIndex-It contains the index where the Action occurs.
SourceCollectionChanged
This event is raised when you make changes in SourceCollection for example add or remove the collection. The event receives two arguments namely sender that handles GridQueryableCollectionViewWrapper object and NotifyCollectionChangedEventArgs as object.
NotifyCollectionChangedEventArgs has the following properties,
Action - It contains the current action. (i.e) Add, Remove, Move, Replace, Reset.
NewItems-It contains the list of new items involved in the change.
OldItems-It contains the list of old items affected by the Action.
NewStartingIndex-It contains the index where the change occurs.
OldStartingIndex-It contains the index where the Action occurs.
The following are the methods associated with View that can be used to defer refresh the view.
Method Name | Description |
---|---|
DeferRefresh | Enter the defer cycle so that you can do all data operations in view and update once. |
BeginInit and EndInit | When BeginInit method is called it suspends all the updates until EndInit method is called. You can perform all the updation with in these methods and update the view at once. |
NOTE
View has properties that are already defined in SfDataGrid. It recommended setting those properties via SfDataGrid.
Complex Property Binding in SfDataGrid
SfDataGrid control supports to bind Complex properties to its columns. You can bind complex properties with any level. You can bind more complex binding paths by using DisplayBinding (binding the Data Model in Non-Edit mode) and ValueBinding (binding the Data model in edit mode) properties present in GridColumn. When you set UseBindingValue property in GridColumn to ‘true’ then Sorting, Grouping and Filtering make use of Binding defined in GridColumn instead of reflection in manipulate data. You can set this property when you bind more complex property paths.
For example, OrderInfo class contains the property Customers of “Customer” class type. The Customer object contains two values: CustomerID and Country. You can define the GridColumns for these Complex properties in the “Property.PropertyName” format.
The following code example illustrates how to create Complex property. For data collection use OrderInfoRepository.cs, file.
public class OrderInfo
{
int orderID;
string customerId;
string country;
string customerName;
string shippingCity;
Customer customer= new Customer();
public int OrderID
{
get { return orderID; }
set { orderID = value; }
}
public string CustomerID
{
get { return customerId; }
set { customerId = value; }
}
public string CustomerName
{
get { return customerName; }
set { customerName = value; }
}
public string Country
{
get { return country; }
set { country = value; }
}
public string ShipCity
{
get { return shippingCity; }
set { shippingCity = value; }
}
public Customer Customers
{
get { return customer; }
set { customer = value; }
}
public OrderInfo(int orderId, string customerName, string country, string
customerId, string shipCity)
{
this.OrderID = orderId;
this.CustomerName = customerName;
this.Country = country;
this.CustomerID = customerId;
this.Customers.CustomerID = customerId;
this.Customers.Country = country;
this.ShipCity = shipCity;
}
}
<syncfusion:SfDataGrid AutoGenerateColumns="False"
ColumnSizer="SizeToHeader"
ItemsSource="{Binding OrderInfoCollection}">
<syncfusion:SfDataGrid.Columns>
<syncfusion:GridTextColumn MappingName="OrderID" />
<syncfusion:GridTextColumn MappingName="Customers.CustomerID" />
<syncfusion:GridTextColumn MappingName="Country" />
<syncfusion:GridTextColumn MappingName="ShipCity" />
</syncfusion:SfDataGrid.Columns>
</syncfusion:SfDataGrid>
Execute the above code to render the following output.
NOTE
SfDataGrid control allows you to set Grouping, Sorting, Filtering and Summaries for Complex property-bound columns. Complex property binding in SfDataGrid does not support LiveDataUpdationMode
Dynamic Object Binding
SfDataGrid control provides extensive support to bind the dynamic object data to SfDataGrid. For more information about dynamic objects, you can refer:
- http://msdn.microsoft.com/en-us/library/vstudio/dd264741.aspx
- http://msdn.microsoft.com/en-us/library/dd264736.aspx
NOTE
Dynamic is not supported in Silverlight hence it is not supported in SfDataGrid also.
The following code example illustrates the dynamic object data creation.
public class TestData : List<dynamic>
{
public TestData()
{
string[] gender = new string[] { "Male", "Female" };
string[] employeeName = new string[]
{
"Sean Jacobson",
"Phyllis Allen",
"Marvin Allen",
"Michael Allen",
"Cecil Allison",
"Oscar Alpert",
"Sandra Altair",
"Selena Alvarado",
"Emilio Alvaro",
"Maxwell Amman",
"Mae Anderson",
"Ramona Ant",
"Sabrina Appeal",
"Hannah Arawakan",
"Kyle Arabela",
};
Random r = new Random();
for (int i = 1; i <= 15; i++)
{
dynamic newObj = new ExpandoObject();
newObj.EmployeeName = employeeName[r.Next(0, 15)];
newObj.EmployeeId = i + 1000;
newObj.EmployeeSalary = i * 1000;
newObj.Gender = gender[r.Next(0, 2)];
newObj.Value = (double)i;
Add(newObj);
}
}
}
The following code example illustrates binding dynamic object data to SfDataGrid.
<Page.DataContext>
<local:TestData />
</Page.DataContext>
<syncfusion:SfDataGrid x:Name="grid"
AutoGenerateColumns="True"
ItemsSource="{Binding}" />
The following screenshot displays the output.
NOTE
Dynamic Object binding in SfDataGrid does not support LiveDataUpdationMode.