未分類

.NET 2 DataGridView

using System;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using OfficeOpenXml;
using OfficeOpenXml.Style;

// Version 1.4
namespace SFRONE
{
    using static C_Common;
    using static D_Original;
    using static D_Const;

    static class C_DataGridView
    {
        // ******************************************
        // *** セルプロパティの設定             *****
        // ******************************************

        public static void DGV_GridUpdating(dataGridViewEX dgvTarget, bool vbON)
        {
            if (vbON)
            {
                dgvTarget.SuspendLayout();
                dgvTarget.ScrollBars = ScrollBars.None;
                //dgvTarget.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None;
                //dgvTarget.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.None;
                //dgvTarget.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
            }
            else
            {
                dgvTarget.ScrollBars = ScrollBars.Both;
                //dgvTarget.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
                //dgvTarget.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
                //dgvTarget.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
                dgvTarget.ResumeLayout();
            }
        }

        // 基本設定
        public static void DGV_BasicSet(DataGridView dgvTarget, bool bSort, bool bAllowUserToAddRows)
        {
            // 一般設定
            dgvTarget.EnableHeadersVisualStyles = false;
            dgvTarget.RowHeadersVisible = false;
            dgvTarget.AllowUserToAddRows = bAllowUserToAddRows;
            dgvTarget.AllowUserToResizeRows = false;
            dgvTarget.BackgroundColor = Color.White;
            dgvTarget.SelectionMode = DataGridViewSelectionMode.CellSelect;
            DGV_RowHeight(dgvTarget);

            // ソート設定
            if (!bSort)
            {
                SortInvalid(dgvTarget);
            }

            // 列のボーダー設定
            dgvTarget.ColumnHeadersBorderStyle = DataGridViewHeaderBorderStyle.Single;

            // 列のアライメント
            foreach (DataGridViewColumn item in dgvTarget.Columns)
            {
                item.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
            }

            // ダブルバッファ設定
            Type dgvtype = typeof(DataGridView);
            PropertyInfo dgvPropertyInfo = dgvtype.GetProperty("DoubleBuffered", BindingFlags.Instance | BindingFlags.NonPublic);
            dgvPropertyInfo.SetValue(dgvTarget, true, null);
        }

        public static void DGV_Column_Show<EnumType>(DataGridView dgvTarget)
        {
            //            if (dgvTarget.Columns.Count != 0) return;

            dgvTarget.Columns.Clear();
            foreach (EnumType item in Enum.GetValues(typeof(EnumType)))
            {
                if (item.ToString().Contains("コード"))
                {
                    dgvTarget.Columns.Add(item.ToString(), "コード");
                }
                else
                {
                    dgvTarget.Columns.Add(item.ToString(), item.ToString());
                }
            }
        }

        // 列のリサイズ
        public static void DGV_Col_Resize(DataGridView dgvTarget, int iTargetColIndex, int iAdjest = 0)
        {
            // 列非表示の場合は処理を中止
            if (dgvTarget.Columns.Count < 1) return;

            // ターゲット列以外の列の合計幅の掲載
            int iSumWidth = 0; // id 非表示列分

            foreach (DataGridViewColumn col in dgvTarget.Columns)
            {
                if (col.Index == iTargetColIndex) continue;

                if (col.Visible)
                {
                    iSumWidth += col.Width;
                }
                else
                {
                    iSumWidth += 0;
                }
            }

            // スクロールバーのサイズ
            int iScrollBarWidth = 0;
            if (dgvTarget.Controls[1].Visible)
            {
                iScrollBarWidth = new VScrollBar().Width + 3;
            }
            else
            {
                iScrollBarWidth = 3;
            }

            // ターゲット列の幅を変更
            int iNewWidth = dgvTarget.ClientSize.Width - iSumWidth - iScrollBarWidth;
            dgvTarget.Columns[iTargetColIndex].Width = iNewWidth - iAdjest;
        }

        // 行のリサイズ
        public static void DGV_RowHeight(DataGridView dgvTarget)
        {
            // 変数の宣言
            int iRowHeight = 25;

            // 行設定
            dgvTarget.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.EnableResizing;
            dgvTarget.ColumnHeadersHeight = iRowHeight;
            dgvTarget.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
            if (dgvTarget.Rows.Count == 1)
            {
                dgvTarget.Rows[0].Height = iRowHeight;
            }
            dgvTarget.RowTemplate.Height = iRowHeight;
            dgvTarget.RowTemplate.MinimumHeight = iRowHeight;
        }

        // 行背景のゼブラ化
        public static void RowBackColor_Change(DataGridView dgvTarget)
        {
            // 変数の宣言
            var rows = dgvTarget.Rows.Cast<DataGridViewRow>().AsEnumerable().Where(row => row.Visible).Select((row, idx) => new { Value = row, Index = idx });

            // 行背景のゼブラ化
            foreach (var row in rows)
            {
                foreach (DataGridViewCell cell in row.Value.Cells.Cast<DataGridViewCell>().AsEnumerable().Where(cell => cell.Style.BackColor != Color_Error))
                {
                    if ((row.Index % 2) == 0)
                    {
                        cell.Style.BackColor = Color.AliceBlue;
                    }
                    else
                    {
                        cell.Style.BackColor = Color.White;
                    }
                }
            }
        }

        // 行背景のゼブラ状態の取得
        public static Color RowColor_Get(DataGridViewRow row)
        {
            if ((row.Index % 2) == 0)
            {
                return Color.AliceBlue;
            }
            else
            {
                return Color.White;
            }
        }

        // リードオンリー設定 (Col Index版)
        //public static void DGV_Column_ReadOnly(DataGridView dgvTarget, int iStartCol)
        //{
        //    // 開始
        //    dgvTarget.SuspendLayout();

        //    // 指定した列の全行をロック
        //    for (int iRowPos = 0; iRowPos < dgvTarget.RowCount; iRowPos++)
        //    {
        //        dgvTarget[iStartCol, iRowPos].ReadOnly = true;
        //    }

        //    // 終了
        //    dgvTarget.ResumeLayout();
        //}

        // リードオンリー設定
        public static void DGV_Column_ReadOnly(DataGridView dgvTarget, DataGridViewColumn Col, Color colorMoji)
        {
            // 開始
            dgvTarget.SuspendLayout();

            // 指定した列の全行をロック
            for (int iRowPos = 0; iRowPos < dgvTarget.RowCount; iRowPos++)
            {
                dgvTarget[Col.Index, iRowPos].ReadOnly = true;
                dgvTarget[Col.Index, iRowPos].Style.ForeColor = colorMoji;
            }

            // 終了
            dgvTarget.ResumeLayout();
        }

        public static void DGV_Column_UnReadOnly(DataGridView dgvTarget, DataGridViewColumn Col, Color colorMoji)
        {
            // 開始
            dgvTarget.SuspendLayout();

            // 指定した列の全行をロック
            for (int iRowPos = 0; iRowPos < dgvTarget.RowCount; iRowPos++)
            {
                dgvTarget[Col.Index, iRowPos].ReadOnly = false;
                dgvTarget[Col.Index, iRowPos].Style.ForeColor = colorMoji;
            }

            // 終了
            dgvTarget.ResumeLayout();
        }

        // ******************************************
        // *** セルロック                       *****
        // ******************************************

        public static void Cell_Lock(DataGridView dgvTarget, object Col)
        {
            var rows = dgvTarget.Rows.Cast<DataGridViewRow>().AsEnumerable().Where(row => DGV_StrValue(row, Col) != "");
            foreach (DataGridViewRow row in rows)
            {
                row.Cells[(int)Col].ReadOnly = true;
                row.Cells[(int)Col].Style.ForeColor = Color_LockColor;
            }
        }

        public static void Cell_Lock_All(DataGridView dgvTarget, int iColPos)
        {
            var rows = dgvTarget.Rows.Cast<DataGridViewRow>().AsEnumerable();
            foreach (DataGridViewRow row in rows)
            {
                row.Cells[iColPos].ReadOnly = true;
                row.Cells[iColPos].Style.ForeColor = Color_LockColor;
            }
        }

        // ******************************************
        // *** セルの値取得                     *****
        // ******************************************

        public static string DGV_StrValue(DataGridViewRow row, int iColPos) // *** 廃止
        {
            string sValue = (row.Cells[iColPos].Value ?? "").ToString().Trim();
            return sValue;
        }

        public static string DGV_StrValue(DataGridViewRow row, object objColName)
        {
            // 処理の中止 (行が null の場合)
            if (row == null) return "";

            string sTemp = (row.Cells[objColName.ToString()].Value ?? "").ToString().Trim();
            return sTemp;
        }

        //public static int DGV_IntValue(DataGridViewRow row, object objColName)
        //{
        //    string sValue = DGV_StrValue(row, objColName);
        //    int iTemp = 0;
        //    Int32.TryParse(sValue, out iTemp);
        //    return iTemp;
        //}

        public static int DGV_IntValue(DataGridViewRow row, object objColName)
        {
            string sValue = DGV_StrValue(row, objColName).Replace(",", "");
            int iTemp = 0;
            Int32.TryParse(sValue, out iTemp);
            return iTemp;
        }

        public static Decimal DGV_DecimalValue(DataGridViewRow row, object objColName)
        {
            string sValue = DGV_StrValue(row, objColName);
            decimal dTemp = 0;
            Decimal.TryParse(sValue, out dTemp);
            return dTemp;
        }

        public static DateTime DGV_DateTimeValue(DataGridViewRow row, object objColName)
        {
            string sValue = DGV_StrValue(row, objColName);
            DateTime dtTemp = new DateTime();
            DateTime.TryParse(sValue, out dtTemp);
            return dtTemp;
        }

        // ******************************************
        // *** ソート                           *****
        // ******************************************

        public static void DGV_SortCompare(DataGridViewSortCompareEventArgs e)
        {
            // 変数の宣言
            decimal iVal1;
            decimal iVal2;
            decimal iVal3;
            bool bRet;

            // 値1が文字列の場合は中止
            bRet = decimal.TryParse((e.CellValue1 ?? "").ToString(), out iVal1);
            if (!bRet) return;

            // 値2が文字列の場合は中止
            bRet = decimal.TryParse((e.CellValue2 ?? "").ToString(), out iVal2);
            if (!bRet) return;

            // 比較
            iVal3 = iVal1 - iVal2;
            if (iVal3 < 0)
                e.SortResult = -1;
            else
                e.SortResult = 1;

            // 終了処理
            e.Handled = true;
        }

        // ソート禁止処理
        public static void SortInvalid(DataGridView dgvTarget)
        {
            // ソート禁止処理
            foreach (DataGridViewColumn item in dgvTarget.Columns)
            {
                item.SortMode = DataGridViewColumnSortMode.NotSortable;
            }
        }

        // ******************************************
        // *** セルの状態取得                   *****
        // ******************************************

        public static bool DGV_RowEmpty(DataGridViewRow dgvRow, int ExceptCol = -1)
        {
            string sRowValue = "";
            foreach (DataGridViewCell dgvCell in dgvRow.Cells)
            {
                if (dgvCell.ColumnIndex != ExceptCol)
                {
                    sRowValue = sRowValue + (dgvCell.Value ?? "").ToString().Trim();
                }
            }

            if (sRowValue.Trim() == "")
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        public static bool RowDataExist(DataGridViewRow dgvRow)
        {
            string sRowValue = "";

            foreach (DataGridViewCell dgvCell in dgvRow.Cells)
            {
                //if (dgvCell.Visible)
                {
                    sRowValue = sRowValue + (dgvCell.Value ?? "").ToString().Trim();
                }
            }

            if (sRowValue.Trim() != "")
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        // ******************************************
        // *** マウス処理                       *****
        // ******************************************
        public static void DGV_MouseRightClick(DataGridView dgvTarget, DataGridViewCellMouseEventArgs e)
        {
            if (dgvTarget.SelectedCells.Count > 1)
            {
                return;
            }

            if (e.Button == MouseButtons.Right)
            {
                if (e.ColumnIndex >= 0 && e.RowIndex >= 0)
                {
                    dgvTarget.CurrentCell = dgvTarget[e.ColumnIndex, e.RowIndex];
                }
            }
        }

        // ******************************************
        // *** コピー・貼り付け                 *****
        // ******************************************

        // セルの値のみコピー
        static public void DGV_Cell_Copy(DataGridView dgvTarget)
        {
            // 処理の中止 (クリップボード内のオブジェクトがnullの場合)
            if (dgvTarget.GetClipboardContent() == null) return;

            // セルの値のみコピー
            dgvTarget.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableWithoutHeaderText;
            Clipboard.SetDataObject(dgvTarget.GetClipboardContent());
        }

        // ヘッダーとセルの値をコピー
        static public void DGV_CellHeader_Copy(DataGridView dgvTarget)
        {
            // 処理の中止 (クリップボード内のオブジェクトがnullの場合)
            if (dgvTarget.GetClipboardContent() == null) return;

            // ヘッダーとセルの値をコピー
            dgvTarget.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableAlwaysIncludeHeaderText;
            Clipboard.SetDataObject(dgvTarget.GetClipboardContent());
        }

        // 貼り付け
        static public void DGV_Cell_Paste(DataGridView dgvTarget)
        {
            // 変数の宣言
            object oContent;
            string[] sClipData;

            // 処理の中止 (カレントセルが空の場合)
            if (dgvTarget.CurrentCell == null)
            {
                return;
            }

            // 処理の中止 (クリップボードが空の場合)
            oContent = Clipboard.GetText();
            if (oContent == null) return;

            // 開始処理
            dgvTarget.SuspendLayout();

            // 選択開始位置を特定
            int MinCol = Int32.MaxValue;
            int MinRow = Int32.MaxValue;
            int MaxCol = 0;
            int MaxRow = 0;

            // コピー先の列・行を確定
            foreach (DataGridViewCell cell in dgvTarget.SelectedCells)
            {
                // 列番号の最小値・最大値
                if (cell.ColumnIndex < MinCol) MinCol = cell.ColumnIndex;
                if (cell.ColumnIndex > MaxCol) MaxCol = cell.ColumnIndex;

                // 行番号の最小値・最大値
                if (cell.RowIndex < MinRow) MinRow = cell.RowIndex;
                if (cell.RowIndex > MaxRow) MaxRow = cell.RowIndex;

                if (cell.ReadOnly == true)
                {
                    MessageBox.Show("書き込み禁止のセルにはコピーはできません。", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
            }

            // クリップボードから貼り付け
            sClipData = ((string)oContent).Split('\n');
            string[] sWork;

            // 1行複数セル→複数行単一セル
            if (sClipData.Length == 1)
            {
                string item = sClipData[0];

                foreach (var iRowPos in Enumerable.Range(MinRow, MaxRow - MinRow + 1))
                {
                    sWork = item.Split('\t');
                    foreach (var iColPos in Enumerable.Range(0, sWork.Length))
                    {
                        if ((MinCol + iColPos) < dgvTarget.Columns.Count)
                        {
                            dgvTarget[MinCol + iColPos, iRowPos].Value = sWork[iColPos];
                        }
                    }
                }
            }
            // 複数行複数セル→複数行単一セル
            else
            {
                int ii = 0;
                foreach (var item in sClipData)
                {
                    if (item == "") continue;

                    sWork = item.Split('\t');
                    foreach (var iColPos in Enumerable.Range(0, sWork.Length))
                    {
                        if ((MinRow + ii) > (dgvTarget.Rows.Count - 1)) break;

                        if ((MinCol + iColPos) < dgvTarget.Columns.Count)
                        {
                            dgvTarget[MinCol + iColPos, MinRow + ii].Value = sWork[iColPos];
                        }
                    }
                    ii++;
                }
            }

            // 終了処理
            dgvTarget.ResumeLayout();
        }

        // 上からコピー
        static public void DGV_Cell_CopyPaste(DataGridView dgvTarget, bool bNewRow)
        {
            // 処理の中止 (カレントセルが null の場合)
            if (dgvTarget.CurrentCell == null) return;

            if (bNewRow)
            {
                if (dgvTarget.CurrentCell.RowIndex == dgvTarget.RowCount - 1)
                {
                    dgvTarget.Rows.Insert(dgvTarget.CurrentCell.RowIndex, 1);
                    dgvTarget.CurrentCell = dgvTarget[dgvTarget.CurrentCell.ColumnIndex, dgvTarget.CurrentCell.RowIndex - 1];
                }
            }

            // 変数の宣言
            int iColPos = dgvTarget.CurrentCell.ColumnIndex;
            int iRowPos = dgvTarget.CurrentCell.RowIndex;

            // 処理を中止 (先頭行の場合)
            if (iRowPos == 0) return;

            // 処理を中止 (空白セルの場合)
            if (dgvTarget[iColPos, iRowPos - 1].Value == null) return;

            // コピー&貼り付け
            string sWork = "";
            foreach (DataGridViewCell dgvCell in dgvTarget.SelectedCells)
            {
                if (!dgvCell.ReadOnly)
                {
                    sWork = DGV_StrValue(dgvTarget.Rows[iRowPos - 1], dgvCell.ColumnIndex);
                    dgvTarget[dgvCell.ColumnIndex, iRowPos].Value = sWork;
                }
            }
        }

        // ******************************************
        // *** 行の挿入・削除                   *****
        // ******************************************

        // 行の挿入
        static public void DGV_RowInsert(DataGridView dgvTarget)
        {
            // 行の挿入
            dgvTarget.Rows.Insert(dgvTarget.CurrentCell.RowIndex, 1);
            dgvTarget.CurrentCell = dgvTarget[dgvTarget.CurrentCell.ColumnIndex, dgvTarget.CurrentCell.RowIndex - 1];
        }

        // 行の削除
        static public void DGV_RowDelete(DataGridView dgvTarget)
        {
            // 処理の中止
            if (dgvTarget.CurrentCell == null) return;
            if ((dgvTarget.CurrentCell.RowIndex + 1) >= dgvTarget.Rows.Count) return;

            // 削除前のカレントセルを保存
            DataGridViewCell cell2 = dgvTarget.CurrentCell;

            // 行の非表示
            RowDelete(dgvTarget, dgvTarget.CurrentCell.RowIndex);

            // 処理の中止 (行の非表示後の状態で再チェック)
            if (dgvTarget.CurrentCell == null) return;
            if ((dgvTarget.CurrentCell.RowIndex + 1) >= dgvTarget.Rows.Count) return;

            // 削除前のセル位置と同じ場所にフォーカス設定
            dgvTarget.CurrentCell = dgvTarget[cell2.ColumnIndex, cell2.RowIndex + 1];
            dgvTarget.Focus();
        }

        static void RowDelete(DataGridView dgvTarget, int iRowIndex)
        {
            // 削除する行のエラー状態を解除
            foreach (DataGridViewCell dgvCell in dgvTarget.Rows[dgvTarget.CurrentCell.RowIndex].Cells)
            {
                dgvCell.Style.BackColor = Color.White;
            }

            // 削除 (非表示)
            dgvTarget.Rows[dgvTarget.CurrentCell.RowIndex].Visible = false;
        }

        static public void SumSelectedValue(dataGridViewEX dgvTarget, Label lblMessage)
        {
            // 処理の中止 (エラーメッセージが表示されている場合)
            if (lblMessage.ForeColor == Color_Error) return;

            // 変数の宣言
            int v_iColIndex = 0;
            string v_sTemp = "";
            Decimal vdTemp = 0;
            Decimal vdSum = 0;
            bool bRet;

            if (dgvTarget.SelectedCells.Count <= 1)
            {
                lblMessage.Text = "";
                return;
            }

            // 選択されたセルの合計を計算
            foreach (DataGridViewCell item in dgvTarget.SelectedCells)
            {
                v_iColIndex = item.ColumnIndex;
                v_sTemp = DGV_StrValue(dgvTarget.Rows[item.RowIndex], v_iColIndex).Replace(",", "");
                bRet = Decimal.TryParse(v_sTemp, out vdTemp);
                if (bRet == false)
                {
                    continue;
                }

                vdSum += Decimal.Parse(v_sTemp);
            }

            // 結果の表示
            lblMessage.ForeColor = Color.White;
            if (vdSum.ToString().Contains("."))
            {
                lblMessage.Text = "選択されたセルの合計:" + 材積_Set(vdSum.ToString());
            }
            else
            {
                lblMessage.Text = "選択されたセルの合計:" + 金額_Set(vdSum.ToString());
            }
        }

        static public void DGV_SumRowClear(dataGridViewEX dgvTarget)
        {
            foreach (DataGridViewCell cell in dgvTarget.Rows[0].Cells)
            {
                cell.Value = "";
            }
        }
    }
}

-未分類