Search code examples
winformsdevexpressxtragrid

Xtragrid SelectionChanged or Alternative


I'm having an issue here.

I have a XtraGrid in winforms with a multiselect mode true, I need to validate if the row I'm selecting, if it matches a condition, select it, if not, deselect it. I'm currently using the SelectionChanged method like this:

private void grdProducts_SelectionChanged(object sender, DevExpress.Data.SelectionChangedEventArgs e)
{
    try
    {
        GridView view = sender as GridView;
        int[] selectedRows = view.GetSelectedRows();
        for (int i = 0; i < selectedRows.Length; i++)
        {
            if (view.IsRowSelected(selectedRows[i]))
            {
                Product product = view.GetRow(selectedRows[i]) as Candidato;
                ProcessStatus processStatus = _procesoStatusService.GetProduct(product.IdProduct);
                if (processStatus.Proccess.Inventory == (int)ProductInventory.Yes)
                {
                    view.UnselectRow(selectedRows[i]);
                    XtraMessageBox.Show("One or more products are currently in inventory.");
                }
            }
        }
    }
    catch (Exception)
    {
        throw;
    }
}

The problem here is when the code reaches the view.UnselectRow(selectedRows[i]); line, the SelectionChanged method is called again and the program send multiple XtraMessageBox.

Any help?


Solution

  • You must use BaseView.BeginSelection method before your code and BaseView.EndSelection method after your code. This will prevent the ColumnView.SelectionChanged event to raise.
    Here is example:

    private void grdProducts_SelectionChanged(object sender, DevExpress.Data.SelectionChangedEventArgs e)
    {
        var view = sender as GridView;
        if (view == null) return;
        view.BeginSelection();
        try
        {
            int[] selectedRows = view.GetSelectedRows();
            for (int i = 0; i < selectedRows.Length; i++)
            {
                if (view.IsRowSelected(selectedRows[i]))
                {
                    Product product = view.GetRow(selectedRows[i]) as Candidato;
                    ProcessStatus processStatus = _procesoStatusService.GetProduct(product.IdProduct);
                    if (processStatus.Proccess.Inventory == (int)ProductInventory.Yes)
                    {
                        view.UnselectRow(selectedRows[i]);
                        XtraMessageBox.Show("One or more products are currently in inventory.");
                    }
                }
            }
        }
        catch (Exception)
        {
            view.EndSelection();
            throw;
        }
        view.EndSelection();        
    }