Columns in Xamarin.Android DataGrid

9 Dec 202112 minutes to read

The SfDataGrid allows you to create and add columns in two ways:

  • Automatic columns generation based on the underlying collection.
  • Manually defining columns in C#.

Automatic columns generation

The SfDataGrid creates columns automatically based on the property SfDataGrid.AutoGenerateColumns.Columns are generated based on type of individual properties in the underlying collection which is set as ItemsSource. For example, GridNumericColumn is added for int type property. Below table shows the column type created for the respective data type. For remaining types, GridTextColumn will be created.

Data Tye Column
string, object GridTextColumn
int, float, double, decimal and it’s respective nullable types GridNumericColumn
DateTime GridDateTimeColumn
bool GridSwitchColumn
enum GridPickerColumn
Bitmap GridImageColumn

You can refer the sample from here to get to know the codes for defining properties in the Model class and populating data for generating different types of column automatically.

AutoGenerateColumns with different modes

The auto generation of the columns in SfDataGrid is based on the SfDataGrid.AutoGenerateColumnsMode property.

The SfDataGrid.AutoGenerateColumnsMode decides a way to create columns when the SfDataGrid.AutoGenerateColumns is set to true. It also decides to retain the grouping and sorting when the ItemsSource is changed.

The SfDataGrid.AutoGenerateColumnsMode is of type AutoGenerateColumnsMode which has the following five options.

Modes Description

None

Stores only the columns defined in the SfDataGrid.Columns collection.
When changing the ItemsSource, the grouping and sorting for explicitly defined SfDataGrid.Columns alone will be retained.

Reset

Retains the columns defined explicitly in the application level and creates columns newly for all the other properties in a data source.
When changing the ItemsSource, the grouping and sorting for explicitly defined SfDataGrid.Columns alone will be retained.

ResetAll

When changing the ItemsSource, the columns for the previous data source are cleared and the columns will be created newly for the new data source. Even when columns are explicitly defined it does not consider the defined columns and creates the column based on the underlying collection.
Further, when changing the ItemsSource, the grouping and sorting for all the columns will be cleared.

RetainOld

When changing the ItemsSource, creates columns for all fields in a data source when the Grid does not have any explicit definition for columns. When columns are defined explicitly, the defined columns alone are retained and new columns are not created.
Similarly, when changing the ItemsSource and when the grid have any explicit definition for columns, the grouping and sorting are retained as it is.

SmartReset

Retains the columns defined explicitly in the application level and the columns with MappingName identical to the properties in the new data source. Creates columns newly for all the other properties in the data source.
Similarly, it retains the grouping and sorting of the columns that are defined explicitly in application level and the columns with MappingName identical to the properties in the new data source.

The default value of SfDataGrid.AutoGenerateColumns property is true and SfDataGrid.AutoGenerateColumnsMode is Reset. Hence by default, the SfDataGrid creates columns automatically for every non-explicitly defined public property in the underlying collection bound to its ItemsSource property.

NOTE

When changing the items source for the SfDataGrid ar runtime, the columns are generated on the basis of option set for SfDataGrid.AutoGenerateColumnsMode.

Customize auto generated columns

When the SfDataGrid.AutoGenerateColumns is true, the SfDataGrid.AutoGeneratingColumn event is raised for each GridColumn. This event receives two arguments namely, sender that is SfDataGrid and AutoGeneratingColumnArgs.

The AutoGeneratingColumnArgs object contains the following properties.

  • Column: This property returns the created column using which can be customized.
  • Cancel: This property cancels the column creation.
  • PropertyType: This property provides the type of underlying model property for which the column is created.

You can skip generating a column by handling the SfDataGrid.AutoGeneratingColumn event as follows.

  • C#
  • dataGrid.AutoGeneratingColumn += GridAutoGeneratingColumns; 
    
    void GridAutoGeneratingColumns(object sender, AutoGeneratingColumnArgs e)
    {
        if (e.Column.MappingName == "EmployeeID")
            e.Cancel = true;
    }

    Customizing the width for auto generated columns as shown below.

  • C#
  • void dataGrid_AutoGeneratingColumn(object sender, AutoGeneratingColumnArgs e){
    if (e.Column.MappingName == "OrderID") {
        e.Column.Width = 100;
        }
    }

    You can also apply formatting for auto generated columns as follows.

  • C#
  • void GridAutoGeneratingColumns(object sender, AutoGeneratingColumnArgs e)
    {
        if (e.Column.MappingName == "Freight") {
            e.Column.Format = "C";
            e.Column.CultureInfo = new CultureInfo ("en-US");
        } else if (e.Column.MappingName == "ShippingDate")
            e.Column.Format = "dd/MM/yyyy";
    }

    You can perform any desired operation based on the property type of the underlying model object as follows.

  • C#
  • void GridAutoGeneratingColumns(object sender,AutoGeneratingColumnEventArgs e)
    {
        if(e.PropertyType == typeof(string))
        {
            // Here we have hidden the columns if the underlying property type is string.
            e.Column.IsHidden = true;
        }
    }

    You can also customize the header text, sorting, alignment, padding, etc. of a column by handling the SfDataGrid.AutoGeneratingEvent.

    Manually generating columns

    The SfDataGrid also allows defining the columns manually by adding the GridColumn objects to the SfDataGrid.Columns collection. In case, if you want only the manually defined columns to be in view, set the SfDataGrid.AutoGenerateColumns property to false. There are different types of columns available in the SfDataGrid and you can create any column through code.

    The following code example illustrates about creating columns manually in the SfDataGrid.

  • C#
  • 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";
    
    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);

    Resizing columns

    The SfDataGrid allows resizing the columns by tapping and dragging the right border of the column headers. Resizing can be enabled or disabled by setting the SfDataGrid.AllowResizingColumn property. A resizing indicator is displayed while resizing a column.

    NOTE

    Resizing considers ‘GridColumn.MinimumWidth’ and ‘GridColumn.MaximumWidth’ of the column and will not resize the minimum and maximum width constraints.

  • C#
  • dataGrid.AllowResizingColumn = true;

    Resizing columns in Xamarin.Android DataGrid
    Resizing columns Onmoved in Xamarin.Android DataGrid

    You can change the column width by tapping and dragging the resizing indicator.

    NOTE

    The resizing indicator appears when tapping the right corner of the column header.

    You can interactively hide a column by setting the GridColumn.MinimumWidth property to zero and resizing the column to a width less than 0.

    Resizing modes

    The SfDataGrid allows two modes of resizing set by using the ‘SfDataGrid.ResizingMode’ property.

    • OnMoved: The resizing indicator is moved based on the touch point and the width of the column is updated as the resizing indicator moves.
    • OnTouchUp: The resizing indicator is moved based on the touch point. However, the width of the column is updated only on a touch up operation.

    NOTE

    The default resizing mode is OnMoved.

    The following image shows the resizing mode OnMoved.

    Resizing modes OnMoved in Xamarin.Android DataGrid

    The following image shows the resizing mode OnTouchUp.

    Resizing mode OnTouchUp in Xamarin.Android DataGrid

    Resizing events

    The resizing operation can be handled using the SfDataGrid.ColumnResizing event. The SfDataGrid.ColumnResizing event is fired upon resizing a column and will be continuously fired till the resizing operation ends. By handling the SfDataGrid.ColumnResizing event, you can also cancel the resizing of a particular column.

    The SfDataGrid.ColumnResizing event provides the following properties through GridResizingEventArgs.

    • Index: Returns the index of the resizing column.
    • NewValue: Returns the current width of the resizing column.
    • ResizingState: Returns the current state of the user-interaction through a value from the ProgressStates enum.
    • Cancel: Returns the Boolean property to cancel the event and the resizing operation.

    Cancel resizing for a column

    You can cancel resizing for a particular column using the SfDataGrid.ColumnResizing event. You can cancel the resizing operation of a column based on the different arguments provided in the GridResizingEventArgs.

    The following code example shows how to cancel resizing for a column using the SfDataGrid.ColumnResizing event using the Index value.

  • C#
  • this.dataGrid.ResizingColumns += dataGrid_ResizingColumns;
        private void DataGrid_ColumnResizing(object sender, GridResizingEventArgs e)
            {
                //Code to end resizing if ColumnIndex is 2
                if (e.Index == 2)
                    e.Cancel = true;
            }

    The below code example shows how to cancel resizing for a column using the SfDataGrid.ColumnResizing event using the NewValue value.

  • C#
  • this.dataGrid.ResizingColumns += dataGrid_ResizingColumns;
        private void DataGrid_ColumnResizing(object sender, GridResizingEventArgs e)
            {
                //Code to end resizing if Column's Width is >= 100
                if (e.NewValue >= 100 ||)
                    e.Cancel = true;
            }

    The below code example shows how to cancel resizing for a column using the SfDataGrid.ColumnResizing event using the ProgressStates value.

  • C#
  • this.dataGrid.ResizingColumns += dataGrid_ResizingColumns;
        private void DataGrid_ColumnResizing(object sender, GridResizingEventArgs e)
            {
                //Code to end resizing if interaction state is Progressing
                if (e.ResizingState = ProgressStates.Progressing)
                    e.Cancel = true;
            }

    Picker closed event

    This event is available for both the GridPickerColumn and the GridDateTimeColumn.The GridPickerColumn.Closed and the GridDateTimeColumn.Closed events will be triggered whenever the “OK” or “Cancel” button is pressed in Picker editor and DateTime editor of the GridPickerColumn and GridDateTimeColumn respectively. This event handler contains the parameter of type PickerClosedEventArgs that contains the following properties.

    • OldValue : Gets the old value of the picker.
    • NewValue : Gets the newly selected value of the picker.
    • Action : Returns string value “Commit” when “Ok” button is pressed or “Cancel” when the “Cancel” button is pressed or the picker view is collapsed by touching outside the picker.
  • C#
  • //For GridPickerColumn event has been raised.
                GridPickerColumn  pickerColumn= new GridPickerColumn() { MappingName = "ShipCountry" };
                pickerColumn.Closed += Closed_Method;
                dataGrid.Columns.Add(pickerColumn);
    
                //For GridDateTimeColumn event has been raised.
                GridDateTimeColumn dateTimeColumn = new GridDateTimeColumn() { MappingName = "ShippingDate" };
                dateTimeColumn.Closed += Closed_Method;
                dataGrid.Columns.Add(dateTimeColumn);
    
                private void Closed_Method(object sender, PickerClosedEventArgs e)
                {
                  var newValue = e.NewValue;
                  var oldValue = e.OldValue;
                  var action = e.Action;
                }