How to sort .NET MAUI SfDataGrid programmatically using a picker?
The .NET MAUI DataGrid (SfDataGrid) allows you to sort DataGridColumn based on the user option by selecting an option in the Picker by handling the SelectionIndexChanged event of the Picker. Sorting can be performed based on the Selected Index from the picker by modifying the SfDataGrid.SortColumnDescriptions collection.
Refer to the code example below to add the columns to be sorted in a Picker.
XAML
<StackLayout> <Picker x:Name="SelectionPicker" Title="Choose" HorizontalOptions="Start" SelectedIndex="0" SelectedIndexChanged="OnSelectionChanged" WidthRequest="150"> <Picker.Items> <x:String>Order ID</x:String> <x:String>Customer ID</x:String> <x:String>Freight</x:String> <x:String>Country</x:String> </Picker.Items> </Picker> <syncfusion:SfDataGrid x:Name="dataGrid" ItemsSource="{Binding OrdersInfo}" AutoGenerateColumnsMode="None" VerticalOptions="FillAndExpand"> <syncfusion:SfDataGrid.Columns> <syncfusion:DataGridNumericColumn MappingName="OrderID" HeaderText="Order ID" Format="d" /> <syncfusion:DataGridTextColumn MappingName="CustomerID" HeaderText="Customer ID"/> <syncfusion:DataGridTextColumn MappingName="Freight" /> <syncfusion:DataGridTextColumn MappingName="Country"/> </syncfusion:SfDataGrid.Columns> </syncfusion:SfDataGrid> </StackLayout>
C#
public void OnSelectionChanged(object sender, EventArgs e) { if (SelectionPicker.SelectedIndex == 0) { this.dataGrid.SortColumnDescriptions.Clear(); this.dataGrid.SortColumnDescriptions.Add(new SortColumnDescription() { ColumnName = "OrderID" }); } else if (SelectionPicker.SelectedIndex == 1) { this.dataGrid.SortColumnDescriptions.Clear(); this.dataGrid.SortColumnDescriptions.Add(new SortColumnDescription() { ColumnName = "CustomerID" }); } else if (SelectionPicker.SelectedIndex == 2) { this.dataGrid.SortColumnDescriptions.Clear(); this.dataGrid.SortColumnDescriptions.Add(new SortColumnDescription() { ColumnName = "Freight" }); } else if (SelectionPicker.SelectedIndex == 3) { this.dataGrid.SortColumnDescriptions.Clear(); this.dataGrid.SortColumnDescriptions.Add(new SortColumnDescription() { ColumnName = "Country" }); } }
Output
Download the complete sample from GitHub.
Conclusion
For current customers, check out our .NET MAUI components from the License and Downloads page. If you are new to Syncfusion®, try our 30-day free trial to check out our .NET MAUI DataGrid and other .NET MAUI components.
Please let us know in the comments section if you have any queries or require clarification. You can also contact us through our support forums, Direct-Trac, or feedback portal. We are always happy to assist you!