How to get the column name on tapping a row in .NET MAUI DataGrid?
In .NET MAUI DataGrid, you can retrieve the column name when tapping a row by using the SfDataGrid.CellTapped event. This event provides the row and column index in its arguments. Therefore, by using the ColumnIndex, you can obtain the column name of the tapped cell in SfDataGrid
.
Refer to the code example below, where the CellTapped event is hooked in the SfDataGrid.
Xaml
<syncfusion:SfDataGrid x:Name="dataGrid"
ColumnWidthMode="Auto"
ItemsSource="{Binding Employees}">
<syncfusion:SfDataGrid.Behaviors>
<Behaviors:DataGridBehavior>
</Behaviors:DataGridBehavior>
</syncfusion:SfDataGrid.Behaviors>
The following code demonstrates how to obtain the column name of the tapped cell using the ColumnIndex obtained from the CellTapped event arguments and display it in a DisplayAlert.
Behavior:
public class DataGridBehavior : Behavior<sfdatagrid>
{
protected override void OnAttachedTo(SfDataGrid dataGrid)
{
dataGrid.CellTapped += SfDataGrid_CellTapped;
base.OnAttachedTo(dataGrid);
}
protected override void OnDetachingFrom(SfDataGrid dataGrid)
{
dataGrid.CellTapped -= SfDataGrid_CellTapped;
base.OnDetachingFrom(dataGrid);
}
private void SfDataGrid_CellTapped(object? sender, DataGridCellTappedEventArgs e)
{
SfDataGrid grid = (SfDataGrid)sender;
int columnIndex;
string columnName;
columnIndex = grid.ResolveToGridVisibleColumnIndex(e.RowColumnIndex.ColumnIndex);
columnName = grid.Columns[columnIndex].MappingName;
Page currentPage = GetParentPage((View)sender);
currentPage.DisplayAlert("Setected Column Name", columnName, "Cancel");
}
private Page GetParentPage(View view)
{
Element parent = view.Parent;
while (parent != null)
{
if (parent is Page page)
return page;
parent = parent.Parent;
}
return null;
}
}
Upon executing the above code and tapping a cell in the SfDataGrid, a DisplayAlert will appear, showing the column name as depicted below.
Download the complete sample from GitHub
Conclusion
I hope you enjoyed learning how to get the column name on tapping a row in .NET MAUI DataGrid.
You can refer to our .NET MAUI DataGrid feature tour page to learn about its other groundbreaking feature representations. Explore our documentation to understand how to present and manipulate data.
For current customers, check out our .NET MAUI components on the License and Downloads page. If you are new to Syncfusion®, try our 30-day free trial to explore 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, or the feedback portal. We are always happy to assist you!