for loop for large data for large data

时间:2017-04-03 16:22:59

标签: c# for-loop devexpress

我正在使用devexpress控件。下面的代码用于selectionChanged事件。当数据量很大时,这种for循环会导致性能降低。有没有办法可以优化这个?

         for (int i = 0; i < gridView.RowCount; i++)
         {
            int currentHandle = gridView.GetVisibleRowHandle(i);
            var row = gridView.GetRow(currentHandle) as xxxx;

            if (gridView.IsRowSelected(currentHandle) && !listSelectedItems.Contains(row))
            {
              listSelectedItems.Add(row);
            }
            else if (!gridView.IsRowSelected(currentHandle) && listSelectedItems.Contains(row))
            {
              listSelectedItems.Remove(row);
            }
         }

         gridControl2.Datasource = listSelectedItems;
         //sometimes refresh datasource is also slow and I tried using beginupdate and endupdate but they never helped
         gridControl2.RefreshDatasource();

1 个答案:

答案 0 :(得分:1)

gridControl2使用BindingList。使用BindingList时,无需每次都刷新gridControl2

private BindingList<SomeClass> _selected;

gridControl2.DataSource = _selected;

SelectionChanged事件中使用SelectionChangedEventArgs对象及其SelectionChangedEventArgs.Action成员。并使用GridView.GetSelectedRows()方法获取视图中的所有选定行 这是一个例子:

private void gridView1_SelectionChanged(object sender, DevExpress.Data.SelectionChangedEventArgs e)
{
    switch (e.Action)
    {
        case CollectionChangeAction.Add:
            var addedRow = (SomeClass)gridView1.GetRow(e.ControllerRow);

            if (!_selected.Contains(addedRow)) //You need this check only when gridView1.OptionsSelection.MultiSelectMode == GridMultiSelectMode.CellSelect
                _selected.Add(addedRow);
            break;
        case CollectionChangeAction.Remove:
            _selected.Remove((SomeClass)gridView1.GetRow(e.ControllerRow));
            break;
        case CollectionChangeAction.Refresh:

            gridView2.BeginDataUpdate();

            _selected.Clear();

            var rows = gridView1.GetSelectedRows().Select(row => (SomeClass)gridView1.GetRow(row));
            foreach (var row in rows)
                _selected.Add(row);

            gridView2.EndDataUpdate();

            break;
    }
}