Getting Started with Xamarin.iOS DataGrid (SfDataGrid)

This section provides a quick overview for working with SfDataGrid for Xamarin.iOS. You will walk through the entire process of creating a real world SfDataGrid.

Assembly deployment

After installing Essential Studio for Xamarin, you can find all the required assemblies in the installation folders,

{Syncfusion Essential Studio Installed location}\Essential Studio\18.2.0.44\Xamarin\lib

Eg: C:\Program Files (x86)\Syncfusion\Essential Studio\18.2.0.44\Xamarin\lib

NOTE

Assemblies can be found in unzipped package location in Mac

NuGet configuration

To install the required NuGet for the SfDataGrid control in the application, configure the NuGet packages of the Syncfusion components.

Refer to the following KB to configure the NuGet packages of the Syncfusion components:

How to configure package source and install Syncfusion NuGet packages in an existing project?

The following NuGet package should be installed to use the SfDataGrid control in the application.

Project Required package
Xamarin.iOS Syncfusion.Xamarin.SfDataGrid.iOS

Adding SfDataGrid Reference

Syncfusion Xamarin components are available in nuget.org. To add SfDataGrid to your project, open the NuGet package manager in Visual Studio, and search for Syncfusion.Xamarin.SfDataGrid.IOS, and then install it.

SfDataGrid in nuget.org

To know more about obtaining our components, refer to this link. Also, if you prefer to manually refer the assemblies instead of NuGet, refer the list of assemblies mentioned in the table below.

Project Required assemblies
Xamarin.iOS Syncfusion.Linq.iOS.dll
Syncfusion.SfDataGrid.iOS.dll
Syncfusion.GridCommon.Portable.dll
Syncfusion.SfNumericTextBox.iOS.dll

To export the SfDataGrid to Excel and PDF formats, search for Syncfusion.Xamarin.SfGridConverter.IOS in the NuGet package manager, and then install it.

DataGridExport in Xamarin.iOS

If you prefer to manually refer the assemblies instead of NuGet, refer the list of assemblies mentioned in the table below.

Project Required assemblies
Xamarin.iOS Syncfusion.SfGridConverter.iOS.dll
pcl\Syncfusion.Compression.Portable.dll
pcl\Syncfusion.Pdf.Portable.dll
pcl\Syncfusion.XlsIO.Portable.dll

IMPORTANT

Starting with v16.2.0.x, if you reference Syncfusion assemblies from trial setup or from the NuGet feed, you also have to include a license key in your projects. Please refer to this link to know about registering Syncfusion license key in your Xamarin application to use our components.

Create a simple SfDataGrid

This section explains how to create a SfDataGrid and configure it. The SfDataGrid control can be configured entirely in C# code or using story board. This is how the final output will look like on iOS devices.

SfDataGrid in Xamarin.iOS

You can download the entire source code of this demo for Xamarin.iOS from here.

In this walk through, you will create a new application that contains the SfDataGrid which includes the below topics.

Creating the project

Create a new iOS application in Xamarin Studio or Visual Studio for Xamarin.iOS.

Adding SfDataGrid in Xamarin.iOS using story board

  1. Add a new story board inside the project.
  2. Drag the SfDataGrid control from toolbox and drop it into the story board. Preview for SfDataGrid will be shown.
  3. Open the properties window of SfDataGrid and set the required properties.

SfDataGrid renderer in designer page

Setting the SfDataGrid properties in story board

Set the identity name and required properties for SfDataGrid in story board.

SfDataGrid properties

Set the identity name and required properties for SfDataPager in story board.

SfDataGrid properties

namespace Grid
{
	public partial class MyViewController : UIViewController
	{
		ViewModel viewModel;
		public MyViewController() : base("MyViewController",null)
		{
		}
		public override void ViewDidLoad()
		{
 			base.ViewDidLoad();
 			// Perform any additional setup loading the view, typically from a nib.
 			viewModel = new ViewModel();
 			sfPager.Source = viewModel.OrdersInfo;
 			sfGrid.ItemSource = sfPager.PagedSource;
		}
		public override void DidReceiveMemoryWarning()
		{
			base.DidReceiveMemoryWarning();
			// Release any cached data, images, etc that aren't in use.
		}
	}
}

You can download the entire source code of this sample here.

Refer to this link to know the properties that can be configured using story board for SfDataGrid.

Adding SfDataGrid in Xamarin.iOS using C# code

  1. Add the required assembly references to the project as discussed in the Assembly deployment section.

  2. Import SfDataGrid control namespace Syncfusion.SfDataGrid.

  3. Create an instance of SfDataGrid control and add as a SubView to a UIViewController.

using Syncfusion.SfDataGrid; 
public partial class GettingStartedViewController : UIViewController
{
    SfDataGrid dataGrid;

    static bool UserInterfaceIdiomIsPhone {
        get { return UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone; }
    }

    public GettingStartedViewController ()
        : base (UserInterfaceIdiomIsPhone ? "GettingStartedViewController_iPhone" : "GettingStartedViewController_iPad", null)
    {
        dataGrid = new SfDataGrid ();
        dataGrid.HeaderRowHeight = 45;
        dataGrid.RowHeight = 45;
    }

    public override void ViewDidLoad ()
    {
        base.ViewDidLoad ();
        dataGrid.Frame = new CGRect (0, 0, View.Frame.Width, View.Frame.Height);
        View.AddSubview (dataGrid);
    }
}

You can also set HeaderRowHeight and RowHeight for SfDataGrid using story board.

SfDataGrid properties

Run the application to render the following output.

SfDataGrid with RowHeight and HeaderRowHeight

The Frame is used to arrange a view in Xamarin.iOS. By default a view in Xamarin.iOS will be arranged without any padding from the title bar. Hence the content of the arranged view will overlap with the title bar if the top position of its Frame is set as 0.

To overcome the above problem, the top position of the view’s Frame has to be customized accordingly to position the view below the title bar in iOS. Refer the below code example in which the top position of the SfDataGrid’s Frame is set to 30 to overcome the problem.

public override void ViewDidLoad ()
{
      base.ViewDidLoad ();
      dataGrid.Frame = new CGRect (0, 30, View.Frame.Width, View.Frame.Height);
      View.AddSubview (dataGrid);
 }

Run the application with the above code to render the following output.

SfDataGrid with top padding

Create DataModel for the SfDataGrid

SfDataGrid is a data-bound control. Hence you must create a data model to bind it to the control.

Create a simple data source as shown in the following code example in a new class file and save it as OrderInfo.cs file.

public class OrderInfo
{
    private int orderID;
    private string customerID;
    private string customer;
    private string shipCity;
    private string shipCountry;

    public int OrderID {
        get { return orderID; }
        set { this.orderID = value; }
    }

    public string CustomerID {
        get { return customerID; }
        set { this.customerID = value; }
    }

    public string ShipCountry {
        get { return shipCountry; }
        set { this.shipCountry = value; }
    }

    public string Customer {
        get { return this.customer; }
        set { this.customer = value; }
    }

    public string ShipCity {
        get { return shipCity; }
        set { this.shipCity = value; }
    }

    public OrderInfo (int orderId, string customerId, string country, string customer, string shipCity)
    {
        this.OrderID = orderId;
        this.CustomerID = customerId;
        this.Customer = customer;
        this.ShipCountry = country;
        this.ShipCity = shipCity;
    }
}

NOTE

If you want your data model to respond to property changes, then implement INotifyPropertyChanged interface in your model class

Create a model repository class with OrderInfo collection property initialized with required number of data objects in a new class file as shown in the following code example and save it as OrderInfoRepository.cs file.

public class OrderInfoRepository
{
    private ObservableCollection<OrderInfo> orderInfo;
    public ObservableCollection<OrderInfo> OrderInfoCollection {
        get { return orderInfo; }
        set { this.orderInfo = value; }
    }

    public OrderInfoRepository ()
    {
        orderInfo = new ObservableCollection<OrderInfo> ();
        this.GenerateOrders ();
    }

    private void GenerateOrders ()
    {
        orderInfo.Add (new OrderInfo (1001, "Maria Anders", "Germany", "ALFKI", "Berlin"));
        orderInfo.Add (new OrderInfo (1002, "Ana Trujillo", "Mexico", "ANATR", "Mexico D.F."));
        orderInfo.Add (new OrderInfo (1003, "Ant Fuller", "Mexico", "ANTON", "Mexico D.F."));
        orderInfo.Add (new OrderInfo (1004, "Thomas Hardy", "UK", "AROUT", "London"));
        orderInfo.Add (new OrderInfo (1005, "Tim Adams", "Sweden", "BERGS", "Lula"));
        orderInfo.Add (new OrderInfo (1006, "Hanna Moos", "Germany", "BLAUS", "Mannheim"));
        orderInfo.Add (new OrderInfo (1007, "Andrew Fuller", "France", "BLONP", "Strasbourg"));
        orderInfo.Add (new OrderInfo (1008, "Martin King", "Spain", "BOLID", "Madrid"));
        orderInfo.Add (new OrderInfo (1009, "Lenny Lin", "France", "BONAP", "Marseilles"));
        orderInfo.Add (new OrderInfo (1010, "John Carter", "Canada", "BOTTM", "Tsawassen"));
        orderInfo.Add (new OrderInfo (1011, "Martin King", "UK", "AROUT", "London"));
        orderInfo.Add (new OrderInfo (1012, "Anne Wilson", "Germany", "BLAUS", "Mannheim"));
        orderInfo.Add (new OrderInfo (1013, "Hanna Kyle", "France", "BLONP", "Strasbourg"));
        orderInfo.Add (new OrderInfo (1014, "Gina Irene", "UK", "AROUT", "London"));
    }
}

Binding data to SfDataGrid

In order to bind the data source of the SfDataGrid, set the SfDataGrid.ItemsSource property as shown below. You can bind the data source of the SfDataGrid as follows.

The following code example binds the collection created in previous step to SfDataGrid.ItemsSource property.

OrderInfoRepository viewModel = new OrderInfoRepository ();
dataGrid.ItemsSource = viewModel.OrderInfoCollection;

Now run the application to render the following output.

Data Virtualization in SfDataGrid for Xamarin.iOS

Defining Columns

By default, the SfDataGrid automatically creates columns for all the properties in the data source. The type of the column generated depends on the type of data in the column. When the columns are auto-generated, you can handle the SfDataGrid.AutoGeneratingColumn event to customize or cancel the columns before they are added to the Columns collection in SfDataGrid.

You can also define the columns manually by setting the SfDataGrid.AutoGenerateColumns property to false and by adding the GridColumn objects to the SfDataGrid.Columns collection. The following code example illustrates how this can be done.

dataGrid.AutoGenerateColumns = false;

GridTextColumn orderIdColumn = new GridTextColumn ();
orderIdColumn.MappingName = "OrderID";
orderIdColumn.HeaderText = "Order ID";

GridTextColumn customerIdColumn = new GridTextColumn ();
customerIdColumn.MappingName = "CustomerID";
customerIdColumn.HeaderText = "Customer ID";

GridTextColumn customerColumn = new GridTextColumn ();
customerColumn.MappingName = "Customer";
customerColumn.HeaderText = "Customer";

GridTextColumn countryColumn = new GridTextColumn ();
countryColumn.MappingName = "ShipCountry";
countryColumn.HeaderText = "Ship Country";

dataGrid.Columns.Add (orderIdColumn);
dataGrid.Columns.Add (customerIdColumn);
dataGrid.Columns.Add (customerColumn);
dataGrid.Columns.Add (countryColumn);

Sorting

SfDataGrid allows you to apply sorting on its data by setting the SfDataGrid.AllowSorting property to true.

You can also set the sorting for SfDataGrid using story board.

Sorting via story board in SfDataGrid fo Xamarin.iOS

dataGrid.AllowSorting = true;

Run the application and touch the header cell to sort the data and the following output will be displayed.

Sorting in SfDataGrid in Xamarin.iOS

You can also configure sorting by adding the column to the SfDataGrid.SortColumnDescriptions collection as below.

dataGrid.SortColumnDescriptions.Add (new SortColumnDescription () { ColumnName = "CustomerID" });

Grouping

SfDataGrid allows you to group a column by adding the column to the SfDataGrid.GroupColumnDescriptions collection as shown below.

dataGrid.GroupColumnDescriptions.Add (new GroupColumnDescription () { ColumnName = "ShipCountry" });

Run the application to render the following output.

Grouping in SfDatGrid in Xamarin.iOS

Selection

SfDataGrid allows you to select the row/rows by setting the SfDataGrid.SelectionMode property. You can set the SfDataGrid.SelectionMode property to single, multiple, single deselect or none based on your requirements. Information about the row/rows selected can be tracked using SfDataGrid.SelectedItem and SfDataGrid.SelectedItems properties.

Loading SfDataGrid with customized height and width

SfDataGrid can be loaded with specific height and width by specifying the height and width of the SfDataGrid.Frame property.

To load SfDataGrid with specific height and width, follow the code example:

public override void ViewDidLayoutSubviews()
{
    dataGrid.Frame = new CGRect(85, 130, 200, 380);
    base.ViewDidLayoutSubviews();
}

You can also set the custom height and width to SfDataGrid using story board.

Custom width and height via story board in SfDataGrid for Xamarin.iOS

The following screenshot shows how the SfDataGrid is loaded with specific height and width:

SfDataGrid with specific heigt and width

Properties configured using story board

Properties Attribute Name
AlternatingRowColor Alternating Row Color
AlternationCount Alternation Count
AllowPullToRefresh Allow Pull To Refresh
AllowLoadMore Allow Load More
AllowEditing Allow Editing
AllowSorting Allow Sorting
AllowMultiSorting Allow Multi Sorting
AllowTriStateSorting Allow Tri State Sorting
AllowDraggingColumn Allow Dragging Column
AllowDraggingRow Allow Dragging Row
AllowResizingColumn Allow Resizing Column
AutoGenerateColumns Auto Generate Columns
AutoGenerateColumnsMode Auto Generate Columns Mode
AutoEllipsisMode Auto Ellipsis Mode
CellBorderStyle Cell Border Style
ColumnSizer Column Sizer
DefaultColumnWidth Default Column Width
DataFetchSize Data Fetch Size
EditTapAction Edit Tap Action
EditorSelectionBehavior Editor Selection Behavior
EnableDataVirtualization Enable Data Virtualization
FrozenRowsCount Frozen Rows Count
FrozenColumnsCount Frozen Columns Count
GroupCaptionTextFormat Group Caption Text Format
GroupingMode Grouping Mode
HeaderRowHeight Header Row Height
IndentColumnWidth Indent Column Width
Orientation Orientation
NumericButtonBackground Numeric Button Background
NumericButtonCount Numeric Button Count
PageCount Page Count
PageSize Page Size
ResizingMode Resizing Mode
RowHeight Row Height
RowHeaderWidth Row Header Width
ScrollingMode Scrolling Mode
SelectionForeground Selection Foreground
SelectionMode Selection Mode
SelectedIndex Selected Index
ShowRowHeader Show Row Header
ShowColumnWhenGrouped Show Column When Grouped
SortTapAction Sort Tap Action
UseOnDemandPaging Use On Demand Paging