[.Net] DataGridView 常用功能製作 Utility

台灣是獨立國家

設置對齊方式,將欄位填滿Grid,檢查該列是否有未填寫欄位,按傳入欄位依序排序

        /// <summary>
        /// 設置對齊方式
        /// </summary>
        /// <param name="align"></param>
        /// <returns></returns>
        public static HorizontalAlignment TransAlign(DataGridViewContentAlignment align)
        {
            switch (align)
            {
                case DataGridViewContentAlignment.TopLeft:
                case DataGridViewContentAlignment.MiddleLeft:
                case DataGridViewContentAlignment.BottomLeft:
                    return HorizontalAlignment.Left;

                case DataGridViewContentAlignment.TopCenter:
                case DataGridViewContentAlignment.MiddleCenter:
                case DataGridViewContentAlignment.BottomCenter:
                    return HorizontalAlignment.Center;

                case DataGridViewContentAlignment.TopRight:
                case DataGridViewContentAlignment.MiddleRight:
                case DataGridViewContentAlignment.BottomRight:
                    return HorizontalAlignment.Right;
            }
            return HorizontalAlignment.Left;
        }

        /// <summary>
        /// 將欄位填滿Grid
        /// </summary>
        /// <param name="grid">欲設定的grid</param>
        /// <param name="Average">平均分配欄寬</param>
        public static void FillAllColumns(DataGridView grid, bool Average)
        {
            foreach (DataGridViewColumn clm in grid.Columns)
            {
                if (!Average && clm.ValueType.IsValueType && clm != grid.Columns[grid.Columns.Count - 1])
                { clm.AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCellsExceptHeader; }
                else { clm.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; }
            }
        }

        /// <summary>
        /// 檢查該列是否有未填寫欄位
        /// </summary>
        /// <param name="row"></param>
        /// <returns></returns>
        public static bool IsRowHasNull(DataGridViewRow row)
        {
            foreach (DataGridViewCell cell in row.Cells)
            { if (Convert.ToString(cell.Value) == string.Empty) { return true; } }
            return false;
        }

        /// <summary>
        /// 按傳入欄位依序排序
        /// </summary>
        /// <param name="grid"></param>
        /// <param name="Columns"></param>
        public static void SetColumnSort(DataGridView grid, params string[] Columns)
        {
            List<String> clmns = new List<String>(Columns);
            foreach (DataGridViewColumn clm in grid.Columns)
            {
                if (clmns.Contains(clm.Name)) { clm.DisplayIndex = clmns.IndexOf(clm.Name); }
                else { clm.DisplayIndex = grid.Columns.Count - 1; }
            }
        }

 

Taiwan is a country. 臺灣是我的國家