Utils/DataGridViewRefresherUtil.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ChatworkBulkSender.Utils;

namespace ChatworkBulkSender.Utils
{
    class DataGridViewRefresherUtil
    {
        /// <summary>
        /// ソート状態を保持するクラス
        /// </summary>
        private class SortState
        {

            /// <summary>
            /// プロパティ名
            /// </summary>
            public string PropertyName { get; set; }

            /// <summary>
            /// ソート済みフラグ
            /// </summary>
            public bool IsSorted { get; set; }

            /// <summary>
            /// 現在のソート順
            /// </summary>
            public ListSortDirection Direction { get; set; }

        }

        public static void RefreshWithState<T>(
            DataGridView dgv,
            Func<List<T>> dataLoader,
            Func<List<T>, object> bindingLIstCreater)
        {
            SortState sortState = null;

            if (dgv.DataSource is SortableBindingListUtil<T> currentBindingList && currentBindingList.IsSorted)
            {
                sortState = new SortState
                {
                    PropertyName = currentBindingList.SortProperty?.Name,
                    IsSorted = true,
                    Direction = currentBindingList.SortDirection
                    ,
                };
            }

            var newData = dataLoader();

            var bindingList = bindingLIstCreater(newData);

            dgv.DataSource = bindingList;

            if (sortState != null && sortState.IsSorted && bindingList is SortableBindingListUtil<T> newSortableList)
            {
                var pd = TypeDescriptor.GetProperties(typeof(T))[sortState.PropertyName];

                if (pd != null)
                {
                    newSortableList[pd] = sortState.Direction;
                    newSortableList.ApplySort(pd);
                }
            }
        }
    }
}