Only allow a specific number of items to be selected

I have a bound sdDatagrid control and have set the selectionmode to Multiple but I only want to 2 items to be selected.

    Private Sub SfDataGrid2_SelectionChanged(sender As Object, e As SelectionChangedEventArgs) Handles SfDataGridOriginalWP.SelectionChanged
        '//Can Only be two sequential Items
        If CType(sender, SfDataGrid).SelectedItems.Count > 2 Then
            CType(sender, SfDataGrid).SelectedItems.RemoveAt(0)
        End If
   End Sub

This I thought would do the trick and remove the 1st item in the collection if it went over resulting in a FIFO type of collection but although the selectedItems reflects only 2 items - the control still highlights and displays all the selected items.   So there appears to be a mismatch between what is showing in the control and what the data is behind the scenes is showing.

Any suggestions or better ways of handling only allowing a specific number of items to be selected.

 

1 Reply 1 reply marked as answer

MA Mohanram Anbukkarasu Syncfusion Team January 13, 2021 06:22 AM UTC

Hi Spotty, 

Thanks for contacting Syncfusion products.  

You can achieve your requirement to allow only a specific number of items to be selected by using the SfDataGrid.SelectionChanging and SfDataGrid.CurrentCellActivating events as shown in the following code example.  

Code example :  

sfDataGrid1.SelectionChanging += SfDataGrid1_SelectionChanging; 
sfDataGrid1.CurrentCellActivating += SfDataGrid1_CurrentCellActivating; 
 
private void SfDataGrid1_SelectionChanging(object sender, Syncfusion.WinForms.DataGrid.Events.SelectionChangingEventArgs e) 
{ 
    if (e.RemovedItems.Count ==0 && (sender as SfDataGrid).SelectedItems.Count == 2) 
        e.Cancel = true; 
} 

private void SfDataGrid1_CurrentCellActivating(object sender, Syncfusion.WinForms.DataGrid.Events.CurrentCellActivatingEventArgs e) 
{ 
    if ((sender as SfDataGrid).SelectedItems.Count == 2 && !(sender as SfDataGrid).SelectedItems.Contains(e.DataRow.RowData)) 
        e.Cancel = true; 
} 


We have prepared a sample using the above given code example and it is available in the following link for your reference.  


Please let us know if you require further assistance from us.  

Regards, 
Mohanram A. 


Marked as answer
Loader.
Up arrow icon