// 下水データ管理システム
// Copyright (C) 2018 公益財団法人とちぎ建設技術センター(https://www.tochigictc.or.jp/)
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.If not, see<http://www.gnu.org/licenses/>.

using ClosedXML.Excel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SQLite;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace WindowsFormsApplication1 {
    public partial class Form1Main : Form {
        public Form1Main() {
            InitializeComponent();
        }

        int cYear = 0;
        int cMonth = 0;

        List<ColumnConfig> ccSet = ColumnsConfigSet.getSet;
        List<int> tabTopColumnNumber = ColumnsConfigSet.tabTopColumnNumber;

        BindingList<KanrisyaSyorijou> KSCBItem = new BindingList<KanrisyaSyorijou>();
        BindingList<SelectableMonth> SMCBItem = new BindingList<SelectableMonth>();

        Color sortColumnHeaderBackColorASC = Color.FromArgb(230, 230, 162);
        Color sortColumnHeaderBackColorDESC = Color.FromArgb(198, 198, 230);
        Color sortColumnBackColorASC = Color.FromArgb(255, 255, 180);
        Color sortColumnBackColorDESC = Color.FromArgb(220, 220, 255);
        Color colorFocus = Color.FromArgb(0, 120, 215);
        Color colorUnFocus = Color.FromArgb(68, 85, 102);

        DataGridViewColumn sortedColumn;
        bool sortedASC;

        Form2InputPreMake win2 = new Form2InputPreMake();
        Form5SettingViewDataPreMake win5 = new Form5SettingViewDataPreMake();
        Form7SettingPrintFormPreMake win7 = new Form7SettingPrintFormPreMake();




        //ロード時イベント
        private void Form1Main_Load(object sender, EventArgs e) {
            FormA1OpeningSplash winSplash1 = new FormA1OpeningSplash();
            winSplash1.Show();
            winSplash1.Refresh();
            dbInitialize(winSplash1);
            dataGridViewInitialize(winSplash1);

            //選択リスト準備
            winSplash1.ProgressMessage = "処理場・月選択リスト準備中";
            Application.DoEvents();

            dataSelectInitialize();
            monthSelectInitialize();

            dataSelectConstruction();
            monthSelectConstruction();

            //データ表示
            winSplash1.ProgressMessage = "データ表示準備中";
            Application.DoEvents();

            suishitsu_kanriSelect();

            //入力フォームの事前生成
            win2.Owner = this;
            win2.WindowState = FormWindowState.Minimized;
            win2.StartPosition = FormStartPosition.CenterParent;
            win2.dgv = dataGridView1;
            win2.preMake = true;
            win2.winSplash = winSplash1;
            win2.ShowDialog();

            win5.Owner = this;
            win5.WindowState = FormWindowState.Minimized;
            win5.StartPosition = FormStartPosition.CenterParent;
            win5.dgv = dataGridView1;
            win5.preMake = true;
            win5.winSplash = winSplash1;
            win5.ShowDialog();

            win7.Owner = this;
            win7.WindowState = FormWindowState.Minimized;
            win7.StartPosition = FormStartPosition.CenterParent;
            win7.dgv = dataGridView1;
            win7.preMake = true;
            win7.winSplash = winSplash1;
            win7.ShowDialog();

            //dataGridView1用ジャンプリスト作成
            makeDataGridViewJumpList();

            //データが必須のメニューの有効無効切替
            hasRowsSwitch();

            //メインメニューに帳票印刷列設定を追加
            makePrintFromSetteigMenu();

            //晴天日判定用雨量条件読込
            SeitenConfigSet.presetSeitenConfigSet();

            winSplash1.Close();
            winSplash1.Dispose();
            this.Activate();
        }




        //表示完了時イベント
        private void Form1Main_Shown(object sender, EventArgs e) {
            dataGridView1.Focus();
        }




        //メインメニューに帳票印刷列設定を追加
        private void makePrintFromSetteigMenu() {
            for(int i = 0; i < MaxSizeConfig.maxPrintForm; i++) {
                ToolStripMenuItem printFormSetting = new ToolStripMenuItem();
                printFormSetting.Text = "帳票" + (i + 1).ToString() + "(&" + (i + 1).ToString("X") + ")";
                printFormSetting.Click += ToolStripMenuItemSettingPrintForm_Click;
                ToolStripMenuItemSettingPrintForm.DropDownItems.Add(printFormSetting);
            }
        }




        //データベース準備
        private void dbInitialize(FormA1OpeningSplash winSplash1) {
            using(var con = new SQLiteConnection(DataBaseConfig.ConnectionString)) {
                con.Open();

                //下水データテーブル
                using(var cmd = con.CreateCommand()) {
                    winSplash1.ProgressMessage = "データベース準備中（0%）";
                    Application.DoEvents();

                    string index = "";
                    cmd.CommandText = "CREATE TABLE IF NOT EXISTS suishitsu_kanri (";

                    foreach(ColumnConfig cc in ccSet) {
                        if(cc.dbColumnType == "mk") {
                            cmd.CommandText += cc.Name + " INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE";
                        }
                        else if(cc.Format == "") {
                            cmd.CommandText += "," + cc.Name + " TEXT";
                        }
                        else if(cc.Format== "N0") {
                            cmd.CommandText += "," + cc.Name + " INTEGER";
                        }
                        else if(cc.Format == "N1" || cc.Format == "N2" || cc.Format == "N3" || cc.Format == "N4" || cc.Format == "N5") {
                            cmd.CommandText += "," + cc.Name + " REAL";
                        }
                        else if(cc.Format.Substring(0, 10) == "yyyy/MM/dd") {
                            cmd.CommandText += "," + cc.Name + " TEXT NOT NULL";
                        }

                        if(cc.dbColumnType == "ix") {
                            index += "CREATE INDEX IF NOT EXISTS " + cc.Name + " ON suishitsu_kanri (" + cc.Name + ");";
                        }
                    }

                    cmd.CommandText += ");";
                    cmd.CommandText += index;
                    cmd.ExecuteNonQuery();

                    winSplash1.ProgressMessage = "データベース準備中（50%）";
                    Application.DoEvents();
                }

                bool tableExist = false;

                //アプリケーション設定テーブル
                using(var cmd = con.CreateCommand()) {
                    tableExist = false;

                    cmd.CommandText = "SELECT name FROM sqlite_master WHERE type='table' AND name='suishitsu_kanri_setting';";

                    using(var reader = cmd.ExecuteReader()) {
                        if(reader.Read()) {
                            tableExist = true;
                        }
                    }

                    cmd.CommandText = "CREATE TABLE IF NOT EXISTS suishitsu_kanri_setting (";
                    cmd.CommandText += "column_name TEXT NOT NULL UNIQUE,";
                    cmd.CommandText += "visible INTEGER,";

                    for(int i=0; i < 10; i++) {
                        cmd.CommandText += "printform" + (i + 1).ToString() + " INTEGER,";
                    }

                    cmd.CommandText += "PRIMARY KEY(column_name)";
                    cmd.CommandText += ");";
                    cmd.ExecuteNonQuery();
                }

                if(!tableExist) {
                    FunctionForDatabase.setSuishitsuKanriRow();
                    FunctionForDatabase.setDefaultSuishitsuKanri();
                }

                winSplash1.ProgressMessage = "データベース準備中（80%）";
                Application.DoEvents();

                //印刷帳票設定テーブル
                using(var cmd = con.CreateCommand()) {
                    tableExist = false;

                    cmd.CommandText = "SELECT name FROM sqlite_master WHERE type='table' AND name='print_form_setting';";

                    using(var reader = cmd.ExecuteReader()) {
                        if(reader.Read()) {
                            tableExist = true;
                        }
                    }

                    cmd.CommandText = "CREATE TABLE IF NOT EXISTS print_form_setting (";
                    cmd.CommandText += "form_no INTEGER NOT NULL UNIQUE,";
                    cmd.CommandText += "name TEXT,";
                    cmd.CommandText += "PRIMARY KEY(form_no)";
                    cmd.CommandText += ");";
                    cmd.ExecuteNonQuery();
                }

                if(!tableExist) {
                    FunctionForDatabase.setPrintFormRow();
                    FunctionForDatabase.setDefaultPrintForm();
                }

                winSplash1.ProgressMessage = "データベース準備中（90%）";
                Application.DoEvents();

                //処理場ごとの雨天判定雨量条件テーブル
                using(var cmd = con.CreateCommand()) {
                    cmd.CommandText = "CREATE TABLE IF NOT EXISTS uten_judge_uryou_setting (";
                    cmd.CommandText += "kanrisya TEXT,";
                    cmd.CommandText += "syorijou TEXT,";
                    cmd.CommandText += "uten_ll_uryou_day0 REAL,";
                    cmd.CommandText += "uten_ll_uryou_day1 REAL,";
                    cmd.CommandText += "uten_ll_uryou_day2 REAL,";
                    cmd.CommandText += "PRIMARY KEY(kanrisya, syorijou)";
                    cmd.CommandText += ");";
                    cmd.ExecuteNonQuery();

                    winSplash1.ProgressMessage = "データベース準備中（100%）";
                    Application.DoEvents();
                }
            }
        }




        //管理者・処理場選択ボックス事前準備
        private void dataSelectInitialize() {
            comboBox1.DisplayMember = "selectionName";
            comboBox1.ValueMember = "primaryKey";
            comboBox1.DataSource = KSCBItem;
            comboBox1.SelectedIndexChanged += new EventHandler(dataSelect_SelectedIndexChanged);
        }




        //月選択ボックス事前準備
        private void monthSelectInitialize() {
            comboBox2.DisplayMember = "selectionName";
            comboBox2.ValueMember = "primaryKey";
            comboBox2.DataSource = SMCBItem;
            comboBox2.SelectedIndexChanged += new EventHandler(monthSelect_SelectedIndexChanged);
        }




        //管理者・処理場選択ボックス生成
        private void dataSelectConstruction(string cKanrisya = null, string cSyorijou = null) {
            comboBox1.SelectedIndexChanged -= dataSelect_SelectedIndexChanged;
            comboBox1.BeginUpdate();
            KSCBItem.Clear();

            using(var con = new SQLiteConnection(DataBaseConfig.ConnectionString)) {
                con.Open();

                using(var cmd = con.CreateCommand()) {
                    cmd.CommandText = "SELECT t1.kanrisya, t1.syorijou, t2.ck FROM suishitsu_kanri AS t1 " +
                        "INNER JOIN (SELECT kanrisya, COUNT(kanrisya) AS ck FROM suishitsu_kanri WHERE del_flg IS NULL GROUP BY kanrisya) AS t2 ON t1.kanrisya = t2.kanrisya " +
                        "GROUP BY t1.kanrisya, t1.syorijou HAVING t2.ck > 0 ORDER BY t2.ck DESC, COUNT(t1.syorijou) DESC";

                    using(var reader = cmd.ExecuteReader()) {
                        int i = 0;
                        int c = 0;
                        while(reader.Read()) {
                            string kanrisya = reader.GetString(0);
                            string syorijou = reader.GetString(1);
                            KSCBItem.Add(new KanrisyaSyorijou(kanrisya, syorijou));

                            if(kanrisya == cKanrisya && syorijou == cSyorijou) {
                                c = i;
                            }

                            i++;
                        }

                        if(i > 0) {
                            comboBox1.Enabled = true;
                            comboBox1.SelectedIndex = c;
                        }
                        else {
                            comboBox1.Enabled = false;
                        }
                    }
                }
            }

            comboBox1.EndUpdate();
            comboBox1.SelectedIndexChanged += new EventHandler(dataSelect_SelectedIndexChanged);
        }




        //月選択ボックス生成
        private void monthSelectConstruction(int cYear = -1, int cMonth = -1) {
            comboBox2.SelectedIndexChanged -= monthSelect_SelectedIndexChanged;
            comboBox2.BeginUpdate();
            SMCBItem.Clear();

            if(comboBox1.SelectedItem != null) {
                comboBox2.Enabled = true;

                KanrisyaSyorijou item1 = (KanrisyaSyorijou)comboBox1.SelectedItem;
                string kanrisya = item1.primaryKey(0);
                string syorijou = item1.primaryKey(1);

                using(var con = new SQLiteConnection(DataBaseConfig.ConnectionString)) {
                    con.Open();

                    using(var cmd = con.CreateCommand()) {
                        cmd.CommandText = "SELECT MIN(sokutei_dt) AS min_dt, MAX(sokutei_dt) AS max_dt FROM suishitsu_kanri WHERE del_flg IS NULL;";

                        using(var reader = cmd.ExecuteReader()) {
                            if(reader.Read()) {
                                if(!reader.IsDBNull(0) && !reader.IsDBNull(1)) {
                                    //全期間
                                    SMCBItem.Add(new SelectableMonth(0, 0));

                                    //存在する年月の最小と最大
                                    DateTime minDt = DateTime.Parse(reader.GetString(0));
                                    DateTime maxDt = DateTime.Parse(reader.GetString(1));

                                    DateTime stDt = DateTime.Parse(minDt.Year.ToString() + "/" + minDt.Month.ToString() + "/1 00:00:00");
                                    DateTime edDt = DateTime.Parse(maxDt.Year.ToString() + "/" + maxDt.Month.ToString() + "/1 00:00:00");

                                    int i = 0;
                                    int c = 0;
                                    for(DateTime cDt = stDt; cDt <= edDt; cDt = cDt.AddMonths(1)) {
                                        DateTime cnDt = cDt.AddMonths(1);

                                        using(var cmd2 = con.CreateCommand()) {
                                            cmd2.CommandText = "SELECT COUNT(*) FROM suishitsu_kanri WHERE kanrisya='" + kanrisya + "' AND syorijou='" + syorijou + "'  AND sokutei_dt>='" + cDt.ToString("yyyy-MM-dd HH:mm:ss") + "' AND sokutei_dt<'" + cnDt.ToString("yyyy-MM-dd HH:mm:ss") + "' AND del_flg IS NULL";

                                            using(var reader2 = cmd2.ExecuteReader()) {
                                                if(reader2.Read()) {
                                                    if(reader2.GetInt32(0) > 0) {
                                                        //選択中の管理者処理場のデータがある月
                                                        SMCBItem.Add(new SelectableMonth(cDt.Year, cDt.Month));
                                                    }
                                                    else {
                                                        //選択中の管理者処理場のデータがない場合は空欄
                                                        SMCBItem.Add(new SelectableMonth(-1, -1));
                                                    }
                                                }
                                            }
                                        }

                                        if(cYear == -1 || cMonth == -1) {
                                            //指定がない場合は今月を選択中に
                                            if(cDt.Year == DateTime.Now.Year && cDt.Month == DateTime.Now.Month) {
                                                c = i + 1;
                                            }
                                        }
                                        else {
                                            if(cDt.Year == cYear && cDt.Month == cMonth) {
                                                c = i + 1;
                                            }
                                        }

                                        i++;
                                    }

                                    comboBox2.SelectedIndex = c;
                                }
                                else {
                                    comboBox2.Enabled = false;
                                }
                            }
                        }
                    }
                }
            }
            else {
                comboBox2.Enabled = false;
            }

            comboBox2.EndUpdate();
            comboBox2.SelectedIndexChanged += new EventHandler(monthSelect_SelectedIndexChanged);
        }




        //管理者・処理場選択ボックス選択変更イベント
        private void dataSelect_SelectedIndexChanged(object sender, EventArgs e) {
            monthSelectConstruction(cYear, cMonth);
            suishitsu_kanriSelect();
            dataGridView1.Focus();
        }




        //月選択ボックス選択変更イベント
        private void monthSelect_SelectedIndexChanged(object sender, EventArgs e) {
            SelectableMonth item2 = (SelectableMonth)comboBox2.SelectedItem;

            if(item2 != null) {
                if(item2.primaryKey(0) != -1 && item2.primaryKey(1) != -1) {
                    cYear = item2.primaryKey(0);
                    cMonth = item2.primaryKey(1);
                }
            }

            suishitsu_kanriSelect();
            dataGridView1.Focus();
        }




        //dataGridView1準備
        private void dataGridViewInitialize(FormA1OpeningSplash winSplash1) {
            //DataGirdViewのプロパティDoubleBufferedをtrueに設定
            Type dataGridViewType = typeof(DataGridView);
            PropertyInfo dataGridViewProperty = dataGridViewType.GetProperty("DoubleBuffered", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
            dataGridViewProperty.SetValue(dataGridView1, true, null);
            dataGridView1.EnableHeadersVisualStyles = false;
            dataGridView1.ColumnHeadersHeight = 34;
            dataGridView1.DefaultCellStyle.SelectionBackColor = colorUnFocus;

            //列作成
            DataGridViewTextBoxColumn[] c = new DataGridViewTextBoxColumn[ccSet.Count];

            decimal stepPer100 = 100M / ccSet.Count;
            decimal setpIntegrate = 0;

            int i = 0;
            foreach(ColumnConfig cc in ccSet) {
                setpIntegrate += stepPer100;

                if(setpIntegrate >= 10) {
                    winSplash1.ProgressMessage = "データ表示欄準備中（" + (Math.Round((decimal)(i + 1) / ccSet.Count * 10M, 0) * 10).ToString() + "%）";
                    Application.DoEvents();
                    setpIntegrate = 0;
                }

                c[i] = new DataGridViewTextBoxColumn();
                c[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.None;
                c[i].Resizable = DataGridViewTriState.False;
                c[i].ReadOnly = true;
                c[i].HeaderText = cc.HeaderText;

                if(!string.IsNullOrEmpty(cc.unit)) {
                    c[i].HeaderText += "\r\n" + cc.unit;
                }
                else {
                    c[i].HeaderCell.Style.WrapMode = DataGridViewTriState.False;
                }

                c[i].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;

                c[i].Name = cc.Name;
                c[i].SortMode = DataGridViewColumnSortMode.NotSortable;
                c[i].Visible = cc.Visible;
                c[i].DefaultCellStyle.Alignment = cc.Alignment;
                c[i].DefaultCellStyle.Format = cc.Format;
                c[i].DefaultCellStyle.NullValue = null;

                dataGridView1.Columns.Add(c[i]);
                i++;
            }

            //列表示非表示設定
            dataGridViewColumnSetting(winSplash1, null);

            //列幅調整
            dataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.ColumnHeader);

            foreach(ColumnConfig cc in ccSet) {
                if(cc.Width != 0) {
                    dataGridView1.Columns[cc.Name].Width = cc.Width;
                }
            }

            //ソートモード設定
            foreach(DataGridViewColumn column in dataGridView1.Columns) {
                column.SortMode = DataGridViewColumnSortMode.Programmatic;
            }

            //測定日列まで固定
            dataGridView1.Columns["sokutei_dt"].Frozen = true;
        }




        //「列の FillWeight 値の合計が 65535 を超えることはできません」例外の対処
        private void dataGridView1_ColumnAdded(object sender, DataGridViewColumnEventArgs e) {
            e.Column.FillWeight = 1;
        }




        //dataGridView1の表示
        private void suishitsu_kanriSelect() {
            KanrisyaSyorijou item1 = (KanrisyaSyorijou)comboBox1.SelectedItem;
            string kanrisya = "";
            string syorijou = "";

            if(item1 != null) {
                kanrisya = item1.primaryKey(0);
                syorijou = item1.primaryKey(1);
            }

            SelectableMonth item2 = (SelectableMonth)comboBox2.SelectedItem;
            int cDtY = -1;
            int cDtM = -1;

            if(item2 != null) {
                cDtY = item2.primaryKey(0);
                cDtM = item2.primaryKey(1);
            }

            DateTime stDt;
            DateTime edDt;
            string dtTerm = "";

            if(cDtY > -1 && cDtM > -1) {
                if(DateTime.TryParse(cDtY + "/" + cDtM + "/01 00:00:00", out stDt)) {
                    edDt = stDt.AddMonths(1);
                    dtTerm = " AND sokutei_dt>='" + stDt.ToString("yyyy-MM-dd HH:mm:ss") + "' AND sokutei_dt<'" + edDt.ToString("yyyy-MM-dd HH:mm:ss") + "'";
                }
            }
            else {
                dtTerm = " AND 0=1";
            }

            using(SQLiteConnection dbCon = new SQLiteConnection(DataBaseConfig.ConnectionString)) {
                DataTable dataTable1 = new DataTable();
                string sql = "SELECT ";

                int i = 0;
                foreach(ColumnConfig cc in ccSet) {
                    if(i > 0) {
                        sql += ", ";
                    }

                    Type t = Type.GetType("System.String");

                    if(cc.Format == "") {
                        sql += cc.Name;
                    }
                    else if(cc.Format == "N0") {
                        t = Type.GetType("System.Int32");
                        sql += cc.Name;
                    }
                    else if(cc.Format == "N1") {
                        t = Type.GetType("System.Decimal");
                        sql += "(" + cc.Name + " / 10) AS " + cc.Name;
                    }
                    else if(cc.Format == "N2") {
                        t = Type.GetType("System.Decimal");
                        sql += "(" + cc.Name + " / 100) AS " + cc.Name;
                    }
                    else if(cc.Format == "N3") {
                        t = Type.GetType("System.Decimal");
                        sql += "(" + cc.Name + " / 1000) AS " + cc.Name;
                    }
                    else if(cc.Format == "N4") {
                        t = Type.GetType("System.Decimal");
                        sql += "(" + cc.Name + " / 10000) AS " + cc.Name;
                    }
                    else if(cc.Format == "N5") {
                        t = Type.GetType("System.Decimal");
                        sql += "(" + cc.Name + " / 100000) AS " + cc.Name;
                    }
                    else if(cc.Format.Substring(0, 10) == "yyyy/MM/dd") {
                        t = Type.GetType("System.DateTime");
                        sql += "strftime('%Y/%m/%d %H:%M:%S'," + cc.Name + ") AS " + cc.Name;
                    }

                    dataTable1.Columns.Add(cc.Name, t);
                    i++;
                }

                SQLiteDataAdapter adapter = new SQLiteDataAdapter(sql + " FROM suishitsu_kanri WHERE kanrisya='" + kanrisya + "' AND syorijou='" + syorijou + "'" + dtTerm + " AND del_flg IS NULL ORDER BY sokutei_dt;", dbCon);

                adapter.Fill(dataTable1);

                dataGridView1.AutoGenerateColumns = false;
                dataGridView1.DataSource = dataTable1;

                i = 0;
                foreach(ColumnConfig cc in ccSet) {
                    dataGridView1.Columns[i].DataPropertyName = cc.Name;
                    i++;
                }
            }

            dataGridView1.Columns["sokutei_dt"].Frozen = true;

            if(sortedColumn == null) {
                sortedColumn = dataGridView1.Columns["sokutei_dt"];
                sortedASC = true;
            }

            dataGridViewSort(dataGridView1, sortedColumn, sortedASC);

            hasRowsSwitch();
        }




        //dataGridView1列表示設定の反映
        private void dataGridViewColumnSetting(FormA1OpeningSplash winSplash1, FormA2ProgressSplash progressSplash1) {
            this.SuspendLayout();

            if(winSplash1 != null) {
                winSplash1.ProgressMessage = "表示データ設定中";
            }

            if(progressSplash1 != null) {
                progressSplash1.ProgressMessage = "表示データ設定中";
            }

            Application.DoEvents();

            //一度すべて表示にする
            foreach(DataGridViewColumn column in dataGridView1.Columns) {
                if(column.Name == "id" || column.Name == "del_flg" || column.Name == "kanrisya" || column.Name == "syorijou") {
                    column.Visible = false;
                }
                else {
                    column.Visible = true;
                }
            }

            //DBの状態をセット
            using(var con = new SQLiteConnection(DataBaseConfig.ConnectionString)) {
                con.Open();

                using(var cmd = con.CreateCommand()) {
                    cmd.CommandText = "SELECT column_name FROM suishitsu_kanri_setting WHERE visible = 0;";

                    using(var reader = cmd.ExecuteReader()) {
                        while(reader.Read()) {
                            string column_name = reader.GetString(0);

                            dataGridView1.Columns[column_name].Visible = false;
                        }
                    }
                }

                con.Close();
            }

            this.ResumeLayout();
        }




        //dataGridView1ダブルクリックイベント
        private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e) {
            DataGridView g = (DataGridView)sender;

            if(g != null && e.RowIndex > -1) {
                int curRow = e.RowIndex;
                suishitsu_kanriUpdate(curRow);
            }
        }




        //dataGridView1フォーカス取得イベント
        private void dataGridView1_Enter(object sender, EventArgs e) {
            pictureBox1.BackColor = colorFocus;
            pictureBox2.BackColor = colorFocus;
            dataGridView1.DefaultCellStyle.SelectionBackColor = colorFocus;
        }




        //dataGridView1フォーカス解除イベント
        private void dataGridView1_Leave(object sender, EventArgs e) {
            if(!comboBox1.Focused && !comboBox2.Focused && !comboBox3.Focused) {
                pictureBox1.BackColor = colorUnFocus;
                pictureBox2.BackColor = colorUnFocus;
                dataGridView1.DefaultCellStyle.SelectionBackColor = colorUnFocus;
            }
        }




        //dataGridView1用ジャンプリスト作成
        private void makeDataGridViewJumpList() {
            comboBox3.Items.Add("列ジャンプ");

            foreach(string tabTitle in InputTab.title) {
                comboBox3.Items.Add(tabTitle);
            }

            comboBox3.SelectedIndex = 0;
        }




        //dataGridView1用ジャンプリスト変更イベント
        private void comboBox3_SelectedIndexChanged(object sender, EventArgs e) {
            if(comboBox3.SelectedIndex != 0) {
                int jumpColumnNo = tabTopColumnNumber[comboBox3.SelectedIndex - 1];

                for(int i = jumpColumnNo; i < dataGridView1.ColumnCount; i++) {
                    if(dataGridView1.Columns[i].Visible && !dataGridView1.Columns[i].Frozen) {
                        dataGridView1.FirstDisplayedScrollingColumnIndex = i;
                        break;
                    }
                }

                comboBox3.SelectedIndex = 0;
            }

            dataGridView1.Focus();
        }




        //キーダウンイベント
        private void dataGridView1_KeyDown(object sender, KeyEventArgs e) {
            int curRow = dataGridView1.CurrentCell.RowIndex;

            //Insertならば追加処理
            if(e.KeyData == Keys.Insert) {
                suishitsu_kanriInsert();
            }

            //EnterかF2なら変更処理
            if(e.KeyData == Keys.Enter || e.KeyData == Keys.F2) {
                suishitsu_kanriUpdate(curRow);

                if(e.KeyData == Keys.Enter) {
                    if(curRow < dataGridView1.RowCount - 1) {
                        SendKeys.Send("{UP}");
                    }
                }
            }

            //Deleteならば削除処理
            if(e.KeyData == Keys.Delete) {
                suishitsu_kanriDelete();
            }
        }




        //データの有無によるボタンの有効無効切替
        private void hasRowsSwitch() {
            //DB内のデータの有無
            if(comboBox1.Enabled) {
                ToolStripMenuItemGraphPrint.Enabled = true;
                button4.Enabled = true;
                ToolStripMenuItemOutputMonthlyReport.Enabled = true;
                button5.Enabled = true;
                ToolStripMenuItemOutputAnnualReport.Enabled = true;
                ToolStripMenuItemOutputQuarterData.Enabled = true;
                ToolStripMenuItemOutputYearData.Enabled = true;
            }
            else {
                ToolStripMenuItemGraphPrint.Enabled = false;
                button4.Enabled = false;
                ToolStripMenuItemOutputMonthlyReport.Enabled = false;
                button5.Enabled = false;
                ToolStripMenuItemOutputAnnualReport.Enabled = false;
                ToolStripMenuItemOutputQuarterData.Enabled = false;
                ToolStripMenuItemOutputYearData.Enabled = false;
            }

            //表示中の処理場・月のデータの有無
            if(dataGridView1.RowCount > 0) {
                ToolStripMenuItemExpExcel.Enabled = true;
                ToolStripMenuItemFormPrint.Enabled = true;
                button3.Enabled = true;
            }
            else {
                ToolStripMenuItemExpExcel.Enabled = false;
                ToolStripMenuItemFormPrint.Enabled = false;
                button3.Enabled = false;
            }
        }




        //dataGridView1列ヘッダークリックイベント
        private void dataGridView1_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e) {
            if(e.Button == MouseButtons.Left) {
                DataGridViewColumn newSortColumn = dataGridView1.Columns[e.ColumnIndex];
                DataGridViewColumn oldSortColumn = dataGridView1.SortedColumn;

                bool sortASC;

                if(oldSortColumn != null) {
                    if(oldSortColumn == newSortColumn) {
                        if(dataGridView1.SortOrder == SortOrder.Ascending) {
                            sortASC = false;
                        }
                        else {
                            sortASC = true;
                        }
                    }
                    else {
                        sortASC = true;
                    }
                }
                else {
                    sortASC = true;
                }

                dataGridViewSort(dataGridView1, newSortColumn, sortASC);
                sortedColumn = newSortColumn;
                sortedASC = sortASC;
            }
        }




        //dataGridView1のソート
        private void dataGridViewSort(DataGridView g, DataGridViewColumn sortColumn, bool sortASC) {
            if(sortASC) {
                g.Sort(sortColumn, ListSortDirection.Ascending);
                sortColumn.HeaderCell.Style.BackColor = sortColumnHeaderBackColorASC;
                sortColumn.DefaultCellStyle.BackColor = sortColumnBackColorASC;
            }
            else {
                g.Sort(sortColumn, ListSortDirection.Descending);
                sortColumn.HeaderCell.Style.BackColor = sortColumnHeaderBackColorDESC;
                sortColumn.DefaultCellStyle.BackColor = sortColumnBackColorDESC;
            }

            foreach(DataGridViewColumn column in g.Columns) {
                if(column != sortColumn) {
                    column.HeaderCell.Style.BackColor = g.ColumnHeadersDefaultCellStyle.BackColor;
                    column.DefaultCellStyle.BackColor = g.DefaultCellStyle.BackColor;
                }
            }
        }




        //dataGridView1右クリックイベント
        private void dataGridView1_CellContextMenuStripNeeded(object sender, DataGridViewCellContextMenuStripNeededEventArgs e) {
            if(e.RowIndex > -1) {
                DataGridView s = (DataGridView)sender;
                e.ContextMenuStrip = contextMenuStrip1;

                if(!s.Rows[e.RowIndex].Selected) {
                    s.ClearSelection();
                    s.Rows[e.RowIndex].Selected = true;
                    toolStripMenuItem1.Enabled = true;
                }
                else {
                    if(s.SelectedRows.Count > 1) {
                        toolStripMenuItem1.Enabled = false;
                    }
                    else {
                        toolStripMenuItem1.Enabled = true;
                    }
                }
            }
        }




        //dataGridView1コンテキストメニュー修正クリックイベント
        private void toolStripMenuItem1_Click(object sender, EventArgs e) {
            suishitsu_kanriUpdate(dataGridView1.SelectedRows[0].Index);
        }




        //dataGridView1コンテキストメニュー削除クリックイベント
        private void toolStripMenuItem2_Click(object sender, EventArgs e) {
            suishitsu_kanriDelete();
        }




        //フォームからの入力処理(修正)
        private void suishitsu_kanriUpdate(int curRow) {
            KanrisyaSyorijou item1 = (KanrisyaSyorijou)comboBox1.SelectedItem;
            string kanrisya = "";
            string syorijou = "";

            if(item1 != null) {
                kanrisya = item1.primaryKey(0);
                syorijou = item1.primaryKey(1);
            }

            SelectableMonth item2 = (SelectableMonth)comboBox2.SelectedItem;
            int cDtY = -1;
            int cDtM = -1;

            if(item2 != null) {
                cDtY = item2.primaryKey(0);
                cDtM = item2.primaryKey(1);
            }

            int topLineRow = 0;

            if(cDtY > -1 && cDtM > -1) {
                topLineRow = dataGridView1.FirstDisplayedScrollingRowIndex;
            }

            int selectedRowIndex = dataGridView1.SelectedRows[0].Index;

            DateTime sokutei_dt = (DateTime)dataGridView1.Rows[curRow].Cells["sokutei_dt"].Value;

            win2.WindowState = FormWindowState.Normal;
            win2.kanrisya = kanrisya;
            win2.syorijou = syorijou;
            win2.curRow = curRow;
            win2.newRecord = false;
            win2.preMake = false;
            win2.ShowDialog();

            //フォームクローズ後の処理
            if(win2.dbChanged) {
                using(var con = new SQLiteConnection(DataBaseConfig.ConnectionString)) {
                    con.Open();

                    //削除フラグのあるレコードをDELETE
                    using(var cmd = con.CreateCommand()) {
                        cmd.CommandText = "DELETE FROM suishitsu_kanri WHERE del_flg = 1;";
                        cmd.ExecuteNonQuery();
                    }

                    //バキューム
                    using(var cmd = con.CreateCommand()) {
                        cmd.CommandText = "VACUUM;";
                        cmd.ExecuteNonQuery();
                    }

                    con.Close();
                }

                //データ再表示
                dataSelectConstruction(win2.kanrisya, win2.syorijou);

                if(cDtY > 0 && cDtM > 0) {
                    //全期間以外の場合は追加した月を表示
                    cDtY = win2.sokutei_dt.Year;
                    cDtM = win2.sokutei_dt.Month;
                }

                monthSelectConstruction(cDtY, cDtM);

                if(sokutei_dt == win2.sokutei_dt && kanrisya == win2.kanrisya && syorijou == win2.syorijou) {
                    //修正後と以前の測定日が同じ、かつ同じ処理場の場合3日後までの晴天日再判定
                    settingSeiten(win2.kanrisya, win2.syorijou, win2.sokutei_dt);
                }
                else {
                    //それ以外の場合対象処理場全件の晴天日再判定
                    FormA2ProgressSplash progressSplash1 = new FormA2ProgressSplash();
                    progressSplash1.Owner = this;
                    progressSplash1.Show();
                    progressSplash1.Refresh();

                    progressSplash1.ProgressMessage = "晴天日判定中";
                    Application.DoEvents();

                    FunctionForDatabase.judgeSeitenUpdateDB(kanrisya, syorijou);

                    progressSplash1.Close();
                    progressSplash1.Dispose();
                    this.Activate();
                }

                suishitsu_kanriSelect();

                if(((cDtY == 0 && cDtM == 0) || (cDtY == win2.sokutei_dt.Year && cDtM == win2.sokutei_dt.Month)) && kanrisya == win2.kanrisya && syorijou == win2.syorijou) {
                    //全期間または修正後の月と以前の月と同じ、かつ同じ処理場の場合、元の位置にスクロール
                    if(topLineRow < (dataGridView1.Rows.Count - 1)) {
                        dataGridView1.FirstDisplayedScrollingRowIndex = topLineRow;
                    }
                    else if(dataGridView1.Rows.Count > 0) {
                        dataGridView1.FirstDisplayedScrollingRowIndex = dataGridView1.Rows.Count - 1;
                    }
                }

                if(dataGridView1.RowCount > 0) {
                    //選択状態を解除
                    dataGridView1.Rows[0].Selected = false;

                    if(((cDtY == 0 && cDtM == 0) || (cDtY == win2.sokutei_dt.Year && cDtM == win2.sokutei_dt.Month)) && kanrisya == win2.kanrisya && syorijou == win2.syorijou) {
                        //全期間または修正後の月と以前の月と同じ、かつ同じ処理場の場合、元の位置を選択状態に
                        if(dataGridView1.RowCount >= selectedRowIndex) {
                            dataGridView1.Rows[selectedRowIndex].Selected = true;
                        }
                    }
                }
            }
        }




        //フォームからの入力処理(追加)
        private void suishitsu_kanriInsert() {
            KanrisyaSyorijou item1 = (KanrisyaSyorijou)comboBox1.SelectedItem;
            string kanrisya = "";
            string syorijou = "";

            if(item1 != null) {
                kanrisya = item1.primaryKey(0);
                syorijou = item1.primaryKey(1);
            }

            SelectableMonth item2 = (SelectableMonth)comboBox2.SelectedItem;
            int cDtY = -1;
            int cDtM = -1;

            if(item2 != null) {
                cDtY = item2.primaryKey(0);
                cDtM = item2.primaryKey(1);
            }

            int topLineRow = 0;

            if(cDtY > -1 && cDtM > -1) {
                topLineRow = dataGridView1.FirstDisplayedScrollingRowIndex;
            }

            win2.WindowState = FormWindowState.Normal;
            win2.kanrisya = kanrisya;
            win2.syorijou = syorijou;
            win2.newRecord = true;
            win2.preMake = false;
            win2.ShowDialog();

            //フォームクローズ後の処理
            if(win2.dbChanged) {
                using(var con = new SQLiteConnection(DataBaseConfig.ConnectionString)) {
                    con.Open();

                    //削除フラグのあるレコードをDELETE
                    using(var cmd = con.CreateCommand()) {
                        cmd.CommandText = "DELETE FROM suishitsu_kanri WHERE del_flg = 1;";
                        cmd.ExecuteNonQuery();
                    }

                    //バキューム
                    using(var cmd = con.CreateCommand()) {
                        cmd.CommandText = "VACUUM;";
                        cmd.ExecuteNonQuery();
                    }

                    con.Close();
                }

                //データ再表示
                dataSelectConstruction(win2.kanrisya, win2.syorijou);

                if(cDtY > 0 && cDtM > 0) {
                    //全期間以外の場合は追加した月を表示
                    cDtY = win2.sokutei_dt.Year;
                    cDtM = win2.sokutei_dt.Month;
                }

                monthSelectConstruction(cDtY, cDtM);

                suishitsu_kanriSelect();

                if(((cDtY == 0 && cDtM == 0) ||(cDtY == win2.sokutei_dt.Year && cDtM == win2.sokutei_dt.Month)) && kanrisya == win2.kanrisya && syorijou == win2.syorijou) {
                    //全期間または追加した月と以前の月と同じ、かつ同じ処理場の場合、元の位置にスクロール
                    if(topLineRow < (dataGridView1.Rows.Count - 1)) {
                        dataGridView1.FirstDisplayedScrollingRowIndex = topLineRow;
                    }
                    else if(dataGridView1.Rows.Count > 0) {
                        dataGridView1.FirstDisplayedScrollingRowIndex = dataGridView1.Rows.Count - 1;
                    }
                }

                //選択状態を解除
                if(dataGridView1.RowCount > 0) {
                    dataGridView1.Rows[0].Selected = false;
                }

                //3日後までの晴天日再判定
                settingSeiten(win2.kanrisya, win2.syorijou, win2.sokutei_dt);
            }
        }




        //削除処理
        private void suishitsu_kanriDelete() {
            if(dataGridView1.SelectedRows.Count < 1 || MessageBox.Show("削除してもよいですか？\n(" + dataGridView1.SelectedRows.Count + "行削除します)", "", MessageBoxButtons.YesNo, MessageBoxIcon.None, MessageBoxDefaultButton.Button2) == DialogResult.No) {
                return;
            }

            KanrisyaSyorijou item1 = (KanrisyaSyorijou)comboBox1.SelectedItem;
            string kanrisya = "";
            string syorijou = "";

            if(item1 != null) {
                kanrisya = item1.primaryKey(0);
                syorijou = item1.primaryKey(1);
            }

            SelectableMonth item2 = (SelectableMonth)comboBox2.SelectedItem;
            int cDtY = -1;
            int cDtM = -1;

            if(item2 != null) {
                cDtY = item2.primaryKey(0);
                cDtM = item2.primaryKey(1);
            }

            int topLineRow = 0;

            if(cDtY > -1 && cDtM > -1) {
                topLineRow = dataGridView1.FirstDisplayedScrollingRowIndex;
            }

            using(var con = new SQLiteConnection(DataBaseConfig.ConnectionString)) {
                con.Open();

                try {
                    //削除フラグのあるレコードをDELETE
                    using(var cmd = con.CreateCommand()) {
                        cmd.CommandText = "DELETE FROM suishitsu_kanri WHERE del_flg = 1;";
                        cmd.ExecuteNonQuery();
                    }

                    //バキューム
                    using(var cmd = con.CreateCommand()) {
                        cmd.CommandText = "VACUUM;";
                        cmd.ExecuteNonQuery();
                    }

                    //削除フラグON
                    using(var cmd = con.CreateCommand()) {
                        string sql1 = "UPDATE suishitsu_kanri SET del_flg = 1 WHERE id IN (";

                        int i = 0;
                        foreach(DataGridViewRow row in dataGridView1.SelectedRows) {
                            if(i > 0) {
                                sql1 += ", ";
                            }

                            sql1 += row.Cells["id"].Value.ToString();
                            i++;
                        }

                        sql1 += ");";

                        cmd.CommandText = sql1;
                        cmd.ExecuteNonQuery();
                    }
                }
                catch(Exception ex) {
                    MessageBox.Show(ex.Message);
                    return;
                }

                con.Close();
            }

            FormA2ProgressSplash progressSplash1 = new FormA2ProgressSplash();
            progressSplash1.Owner = this;
            progressSplash1.Show();
            progressSplash1.Refresh();

            progressSplash1.ProgressMessage = "晴天日判定中";
            Application.DoEvents();

            //対象処理場全件の晴天日再判定
            FunctionForDatabase.judgeSeitenUpdateDB(kanrisya, syorijou);

            progressSplash1.Close();
            progressSplash1.Dispose();
            this.Activate();

            //データ再表示
            dataSelectConstruction(kanrisya, syorijou);

            monthSelectConstruction(cDtY, cDtM);

            suishitsu_kanriSelect();

            //行がある場合、元の位置にスクロール
            if(dataGridView1.FirstDisplayedScrollingRowIndex >= 0) {
                if(topLineRow < (dataGridView1.Rows.Count - 1)) {
                    dataGridView1.FirstDisplayedScrollingRowIndex = topLineRow;
                }
                else if(dataGridView1.Rows.Count > 0) {
                    dataGridView1.FirstDisplayedScrollingRowIndex = dataGridView1.Rows.Count - 1;
                }

                dataGridView1.Rows[0].Selected = false;
            }
        }




        //晴天日判定書込み
        private void settingSeiten(string kanrisya, string syorijou, DateTime sokutei_dt) {
            //DB更新
            FunctionForDatabase.judgeSeitenUpdateDB(kanrisya, syorijou, sokutei_dt);

            //DataGridView更新
            for(int i = 0; i < 3; i++) {
                DataGridViewRow row = dataGridView1.Rows.Cast<DataGridViewRow>().FirstOrDefault(r => (DateTime)r.Cells["sokutei_dt"].Value == sokutei_dt.AddDays(i));

                if(row != null) {
                    bool seiten = Calculate2ndValue.judgeSeiten(kanrisya, syorijou, sokutei_dt.AddDays(i));

                    if(seiten) {
                        row.Cells["seiten"].Value = "○";
                    }
                    else {
                        row.Cells["seiten"].Value = null;
                    }
                }
            }
        }




        //帳票出力フォーム表示
        private void outputPrintForm() {
            var win = new Form31PrintPreviewPrintForm();
            win.Owner = this;
            win.dataGridView1 = dataGridView1;
            win.comboBox1 = comboBox1;
            win.comboBox2 = comboBox2;
            win.WindowState = this.WindowState;
            win.Height = this.Size.Height;
            win.Width = this.Size.Width;
            win.StartPosition = FormStartPosition.CenterParent;
            win.ShowDialog();
            win.Dispose();
        }




        //グラフ出力フォーム表示
        private void outputGraph() {
            var win = new Form32PrintPreviewGraph();
            win.Owner = this;
            win.dataGridView1 = dataGridView1;
            win.comboBox1 = comboBox1;
            win.comboBox2 = comboBox2;
            win.WindowState = this.WindowState;
            win.Height = this.Size.Height;
            win.Width = this.Size.Width;
            win.StartPosition = FormStartPosition.CenterParent;
            win.ShowDialog();
            win.Dispose();
        }




        //月報出力フォーム表示
        private void outputMonthlyReport() {
            var win = new FormD1MonthlyReportSelect();
            win.Owner = this;
            win.StartPosition = FormStartPosition.CenterParent;
            win.ShowDialog();
            win.Dispose();
        }




        //年報出力フォーム表示
        private void outputAnnualReport() {
            var win = new FormD2AnnualReportSelect();
            win.Owner = this;
            win.StartPosition = FormStartPosition.CenterParent;
            win.ShowDialog();
            win.Dispose();
        }




        //四半期毎集計データ出力フォーム表示
        private void outputQuarterData() {
            var win = new FormD3QuarterDataSelect();
            win.Owner = this;
            win.StartPosition = FormStartPosition.CenterParent;
            win.ShowDialog();
            win.Dispose();
        }




        //年度毎集計データ出力フォーム表示
        private void outputYearData() {
            var win = new FormD4YearDataSelect();
            win.Owner = this;
            win.StartPosition = FormStartPosition.CenterParent;
            win.ShowDialog();
            win.Dispose();
        }




        //データエクスポート
        private void dataExportExcel() {
            SaveFileDialog saveFileDialog1 = new SaveFileDialog();

            KanrisyaSyorijou item1 = (KanrisyaSyorijou)comboBox1.SelectedItem;
            string kanrisya = item1.primaryKey(0);
            string syorijou = item1.primaryKey(1);

            SelectableMonth item2 = (SelectableMonth)comboBox2.SelectedItem;
            int cDtY = item2.primaryKey(0);
            int cDtM = item2.primaryKey(1);

            string kikan;

            if(cDtY < 1 || cDtM < 1) {
                kikan = "全期間";
            }
            else {
                kikan = ("0000" + cDtY.ToString()).Substring(cDtY.ToString().Length, 4) + ("00" + cDtM.ToString()).Substring(cDtM.ToString().Length, 2);
            }

            string fileName = "下水データ_" + kanrisya + "_" + syorijou + "_" + kikan;
            string fileNameExtension = "xlsx";

            saveFileDialog1.FileName = fileName + "." + fileNameExtension;
            saveFileDialog1.InitialDirectory = @"%USERPROFILE%\Desktop";
            saveFileDialog1.Filter = "Excel ブック(*.xlsx)|*.xlsx";
            saveFileDialog1.FilterIndex = 1;
            saveFileDialog1.Title = "データエクスポート";
            saveFileDialog1.RestoreDirectory = true;
            saveFileDialog1.OverwritePrompt = true;
            saveFileDialog1.CheckPathExists = true;

            //ダイアログの表示
            if(saveFileDialog1.ShowDialog() == DialogResult.OK) {
                FormA2ProgressSplash progressSplash1 = new FormA2ProgressSplash();
                progressSplash1.Owner = this;
                progressSplash1.Show();
                progressSplash1.Refresh();

                fileName = saveFileDialog1.FileName;
                fileNameExtension = fileName.Substring(fileName.Length - 5);

                if(fileNameExtension != ".xlsx") {
                    fileName += ".xlsx";
                }

                XLWorkbook workbook1 = new XLWorkbook();

                //データのシート
                IXLWorksheet worksheet1 = workbook1.Worksheets.Add("data");

                //見出し行
                int R = 1;
                int C = 0;

                for(int j = 0; j < dataGridView1.ColumnCount; j++) {
                    if(dataGridView1.Columns[j].HeaderText != "id" && dataGridView1.Columns[j].HeaderText != "del_flg") {
                        C++;
                        worksheet1.Cell(R, C).SetValue(dataGridView1.Columns[j].HeaderText);
                        worksheet1.Cell(R, C).SetDataType(XLDataType.Text);
                        worksheet1.Cell(R, C).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
                        worksheet1.Cell(R, C).Style.Font.Bold = true;

                        if(ccSet[j].calculatedDecimal || ccSet[j].calculatedString || ccSet[j].Name == "input_dt") {
                            worksheet1.Cell(R, C).Style.Fill.BackgroundColor = XLColor.LightSteelBlue;
                        }
                    }
                }

                //データ行
                decimal stepPer100 = 100M / dataGridView1.RowCount;
                decimal setpIntegrate = 0;

                for(int i = 0; i < dataGridView1.RowCount; i++) {
                    R = i + 2;
                    C = 0;

                    setpIntegrate += stepPer100;

                    if(setpIntegrate >= 10) {
                        progressSplash1.ProgressMessage = "データ出力中（" + (Math.Round((i + 1M) / dataGridView1.RowCount * 10M, 0) * 10).ToString() + "%）";
                        Application.DoEvents();
                        setpIntegrate = 0;
                    }

                    for(int j = 0; j < dataGridView1.ColumnCount; j++) {
                        if(dataGridView1.Columns[j].HeaderText != "id" && dataGridView1.Columns[j].HeaderText != "del_flg") {
                            C++;

                            string cA = dataGridView1.Columns[j].DefaultCellStyle.Alignment.ToString();
                            string cF = dataGridView1.Columns[j].DefaultCellStyle.Format.ToString();
                            string cV = dataGridView1.Rows[i].Cells[j].Value.ToString();
                            DateTime cVT;
                            decimal cVD;

                            if(cF == "yyyy/MM/dd ddd HH:mm:ss" || cF == "yyyy/MM/dd ddd") {
                                if(DateTime.TryParse(cV, out cVT)) {
                                    worksheet1.Cell(R, C).Value = cVT;
                                }

                                if(cF == "yyyy/MM/dd ddd HH:mm:ss") {
                                    worksheet1.Cell(R, C).SetDataType(XLDataType.DateTime);
                                    worksheet1.Cell(R, C).Style.NumberFormat.Format = "yyyy/MM/dd aaa HH:mm:ss";
                                }
                                else if(cF == "yyyy/MM/dd ddd") {
                                    worksheet1.Cell(R, C).SetDataType(XLDataType.DateTime);
                                    worksheet1.Cell(R, C).Style.NumberFormat.Format = "yyyy/MM/dd aaa";
                                }
                            }
                            else if(cF == "N0" || cF == "N1" || cF == "N2" || cF == "N3" || cF == "N4" || cF == "N5") {
                                if(decimal.TryParse(cV, out cVD)) {
                                    worksheet1.Cell(R, C).Value = cVD;
                                }

                                if(cF == "N0") {
                                    worksheet1.Cell(R, C).Style.NumberFormat.Format = "#,##0";
                                }
                                else if(cF == "N1") {
                                    worksheet1.Cell(R, C).Style.NumberFormat.Format = "#,##0.0";
                                }
                                else if(cF == "N2") {
                                    worksheet1.Cell(R, C).Style.NumberFormat.Format = "#,##0.00";
                                }
                                else if(cF == "N3") {
                                    worksheet1.Cell(R, C).Style.NumberFormat.Format = "#,##0.000";
                                }
                                else if(cF == "N4") {
                                    worksheet1.Cell(R, C).Style.NumberFormat.Format = "#,##0.0000";
                                }
                                else if(cF == "N5") {
                                    worksheet1.Cell(R, C).Style.NumberFormat.Format = "#,##0.00000";
                                }
                            }
                            else {
                                worksheet1.Cell(R, C).SetValue(cV);
                                worksheet1.Cell(R, C).SetDataType(XLDataType.Text);
                            }

                            if(cA == "MiddleCenter") {
                                worksheet1.Cell(R, C).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
                            }
                            else if(cA == "MiddleRight") {
                                worksheet1.Cell(R, C).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Right;
                            }
                            else {
                                worksheet1.Cell(R, C).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Left;
                            }

                            if(ccSet[j].calculatedDecimal || ccSet[j].calculatedString || ccSet[j].Name == "input_dt") {
                                worksheet1.Cell(R, C).Style.Fill.BackgroundColor = XLColor.LightSteelBlue;
                            }
                        }
                    }
                }

                progressSplash1.ProgressMessage = "ワークシート成型中";
                Application.DoEvents();

                worksheet1.SheetView.Freeze(1, 3);
                worksheet1.Range(1, 1, 1, C).Style.Border.InsideBorder = XLBorderStyleValues.Thin;
                worksheet1.Range(1, 1, 1, C).Style.Border.OutsideBorder = XLBorderStyleValues.Thin;
                worksheet1.Range(1, 1, R, C).Style.Font.SetFontSize(9.0).Font.SetFontName("Meiryo UI");
                worksheet1.Range(1, 1, R, C).Style.Alignment.Vertical = XLAlignmentVerticalValues.Center;
                worksheet1.ColumnsUsed().AdjustToContents();

                //設定のシート
                if(!SeitenConfigSet.isNull(kanrisya, syorijou)) {
                    progressSplash1.ProgressMessage = "設定出力中";
                    Application.DoEvents();

                    IXLWorksheet worksheet2 = workbook1.Worksheets.Add("uten_judge_uryou_setting");

                    //見出し行
                    R = 1;
                    C = 0;

                    C++;
                    worksheet2.Cell(R, C).SetValue("管理者");
                    worksheet2.Cell(R, C).SetDataType(XLDataType.Text);
                    worksheet2.Cell(R, C).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
                    worksheet2.Cell(R, C).Style.Font.Bold = true;

                    C++;
                    worksheet2.Cell(R, C).SetValue("処理場");
                    worksheet2.Cell(R, C).SetDataType(XLDataType.Text);
                    worksheet2.Cell(R, C).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
                    worksheet2.Cell(R, C).Style.Font.Bold = true;

                    C++;
                    worksheet2.Cell(R, C).SetValue("雨天条件(当日)");
                    worksheet2.Cell(R, C).SetDataType(XLDataType.Text);
                    worksheet2.Cell(R, C).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
                    worksheet2.Cell(R, C).Style.Font.Bold = true;

                    C++;
                    worksheet2.Cell(R, C).SetValue("雨天条件(1日前)");
                    worksheet2.Cell(R, C).SetDataType(XLDataType.Text);
                    worksheet2.Cell(R, C).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
                    worksheet2.Cell(R, C).Style.Font.Bold = true;

                    C++;
                    worksheet2.Cell(R, C).SetValue("雨天条件(2日前)");
                    worksheet2.Cell(R, C).SetDataType(XLDataType.Text);
                    worksheet2.Cell(R, C).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
                    worksheet2.Cell(R, C).Style.Font.Bold = true;

                    //データ行
                    R++;
                    C = 0;

                    C++;
                    worksheet2.Cell(R, C).SetValue(kanrisya);
                    worksheet2.Cell(R, C).SetDataType(XLDataType.Text);
                    worksheet2.Cell(R, C).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Left;

                    C++;
                    worksheet2.Cell(R, C).SetValue(syorijou);
                    worksheet2.Cell(R, C).SetDataType(XLDataType.Text);
                    worksheet2.Cell(R, C).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Left;

                    C++;
                    worksheet2.Cell(R, C).SetValue(SeitenConfigSet.getUtenLLUryouDay0(kanrisya, syorijou));
                    worksheet2.Cell(R, C).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Right;

                    C++;
                    worksheet2.Cell(R, C).SetValue(SeitenConfigSet.getUtenLLUryouDay1(kanrisya, syorijou));
                    worksheet2.Cell(R, C).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Right;

                    C++;
                    worksheet2.Cell(R, C).SetValue(SeitenConfigSet.getUtenLLUryouDay2(kanrisya, syorijou));
                    worksheet2.Cell(R, C).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Right;

                    worksheet2.Range(1, 1, R, C).Style.Border.InsideBorder = XLBorderStyleValues.Thin;
                    worksheet2.Range(1, 1, R, C).Style.Border.OutsideBorder = XLBorderStyleValues.Thin;
                    worksheet2.Range(1, 1, R, C).Style.Font.SetFontSize(9.0).Font.SetFontName("Meiryo UI");
                    worksheet2.Range(1, 1, R, C).Style.Alignment.Vertical = XLAlignmentVerticalValues.Center;
                    worksheet2.ColumnsUsed().AdjustToContents();
                }

                //ファイル保存
                progressSplash1.ProgressMessage = "ファイル保存中";
                Application.DoEvents();

                try {
                    workbook1.SaveAs(fileName);
                    MessageBox.Show("データのエクスポートが完了しました");
                }
                catch {
                    MessageBox.Show("ファイルが使用中等の理由により、保存できませんでした");
                }

                progressSplash1.Close();
                progressSplash1.Dispose();
                this.Activate();
            }
        }




        //データインポート用ひな形出力
        private void outputDataTemplate() {
            SaveFileDialog saveFileDialog1 = new SaveFileDialog();

            string kanrisya = "";
            string syorijou = "";

            if(comboBox1.Enabled) {
                KanrisyaSyorijou item1 = (KanrisyaSyorijou)comboBox1.SelectedItem;
                kanrisya = item1.primaryKey(0);
                syorijou = item1.primaryKey(1);
            }

            DateTime cDateT = DateTime.Parse(DateTime.Now.Year.ToString() + "/" + DateTime.Now.Month.ToString() + "/01 00:00:00");

            if(comboBox2.Enabled) {
                SelectableMonth item2 = (SelectableMonth)comboBox2.SelectedItem;

                int cDtY = item2.primaryKey(0);
                int cDtM = item2.primaryKey(1);

                if(cDtY > 0 && cDtM > 0) {
                    cDateT = DateTime.Parse(cDtY.ToString() + "/" + cDtM.ToString() + "/01 00:00:00");
                }
            }

            string fileName = "下水データ_ひな形";
            string fileNameExtension = "xlsx";

            saveFileDialog1.FileName = fileName + "." + fileNameExtension;
            saveFileDialog1.InitialDirectory = @"%USERPROFILE%\Desktop";
            saveFileDialog1.Filter = "Excel ブック(*.xlsx)|*.xlsx";
            saveFileDialog1.FilterIndex = 1;
            saveFileDialog1.Title = "データインポート用ひな形出力";
            saveFileDialog1.RestoreDirectory = true;
            saveFileDialog1.OverwritePrompt = true;
            saveFileDialog1.CheckPathExists = true;

            //ダイアログの表示
            if(saveFileDialog1.ShowDialog() == DialogResult.OK) {
                FormA2ProgressSplash progressSplash1 = new FormA2ProgressSplash();
                progressSplash1.Owner = this;
                progressSplash1.Show();
                progressSplash1.Refresh();

                progressSplash1.ProgressMessage = "ファイル出力中";
                Application.DoEvents();

                fileName = saveFileDialog1.FileName;
                fileNameExtension = fileName.Substring(fileName.Length - 5);

                if(fileNameExtension != ".xlsx") {
                    fileName += ".xlsx";
                }

                XLWorkbook workbook1 = new XLWorkbook();

                //データのシート
                IXLWorksheet worksheet1 = workbook1.Worksheets.Add("data");

                //見出し行
                int R = 1;
                int C = 0;

                for(int j = 0; j < dataGridView1.ColumnCount; j++) {
                    if(ccSet[j].Name == "id" || ccSet[j].Name == "del_flg") {
                        continue;
                    }

                    if(!dataGridView1.Columns[j].Visible && !(ccSet[j].Name == "kanrisya" || ccSet[j].Name == "syorijou" || ccSet[j].Name == "sokutei_dt")) {
                        continue;
                    }

                    if(ccSet[j].calculatedDecimal || ccSet[j].calculatedString || ccSet[j].Name == "input_dt") {
                        continue;
                    }

                    C++;
                    worksheet1.Cell(R, C).SetValue(dataGridView1.Columns[j].HeaderText);
                    worksheet1.Cell(R, C).SetDataType(XLDataType.Text);
                    worksheet1.Cell(R, C).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
                    worksheet1.Cell(R, C).Style.Font.Bold = true;
                    worksheet1.Cell(R, C).Style.Fill.BackgroundColor = XLColor.LightGray;
                }

                //データ行
                R = 2;
                C = 0;

                for(int j = 0; j < dataGridView1.ColumnCount; j++) {
                    if(ccSet[j].Name == "id" || ccSet[j].Name == "del_flg") {
                        continue;
                    }

                    if(!ccSet[j].Visible && !(ccSet[j].Name == "kanrisya" || ccSet[j].Name == "syorijou" || ccSet[j].Name == "sokutei_dt")) {
                        continue;
                    }

                    if(ccSet[j].calculatedDecimal || ccSet[j].calculatedString || ccSet[j].Name == "input_dt") {
                        continue;
                    }

                    C++;

                    string cA = dataGridView1.Columns[j].DefaultCellStyle.Alignment.ToString();
                    string cF = dataGridView1.Columns[j].DefaultCellStyle.Format.ToString();

                    if(cF == "yyyy/MM/dd ddd HH:mm:ss") {
                        worksheet1.Cell(R, C).SetDataType(XLDataType.DateTime);
                        worksheet1.Cell(R, C).Style.NumberFormat.Format = "yyyy/MM/dd aaa HH:mm:ss";
                    }
                    else if(cF == "yyyy/MM/dd ddd") {
                        worksheet1.Cell(R, C).SetDataType(XLDataType.DateTime);
                        worksheet1.Cell(R, C).Style.NumberFormat.Format = "yyyy/MM/dd aaa";
                    }
                    else if(cF == "N0") {
                        worksheet1.Cell(R, C).Style.NumberFormat.Format = "#,##0";
                    }
                    else if(cF == "N1") {
                        worksheet1.Cell(R, C).Style.NumberFormat.Format = "#,##0.0";
                    }
                    else if(cF == "N2") {
                        worksheet1.Cell(R, C).Style.NumberFormat.Format = "#,##0.00";
                    }
                    else if(cF == "N3") {
                        worksheet1.Cell(R, C).Style.NumberFormat.Format = "#,##0.000";
                    }
                    else if(cF == "N4") {
                        worksheet1.Cell(R, C).Style.NumberFormat.Format = "#,##0.0000";
                    }
                    else if(cF == "N5") {
                        worksheet1.Cell(R, C).Style.NumberFormat.Format = "#,##0.00000";
                    }
                    else {
                        worksheet1.Cell(R, C).SetDataType(XLDataType.Text);
                    }

                    if(cA == "MiddleCenter") {
                        worksheet1.Cell(R, C).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
                    }
                    else if(cA == "MiddleRight") {
                        worksheet1.Cell(R, C).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Right;
                    }
                    else {
                        worksheet1.Cell(R, C).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Left;
                    }

                    if(ccSet[j].Name == "kanrisya") {
                        worksheet1.Cell(R, C).Value = kanrisya;
                    }
                    else if(ccSet[j].Name == "syorijou") {
                        worksheet1.Cell(R, C).Value = syorijou;
                    }
                    else if(ccSet[j].Name == "sokutei_dt") {
                        worksheet1.Cell(R, C).Value = cDateT;
                    }
                }

                progressSplash1.ProgressMessage = "ワークシート成型中";
                Application.DoEvents();

                worksheet1.SheetView.Freeze(1, 3);
                worksheet1.Range(1, 1, 1, C).Style.Border.InsideBorder = XLBorderStyleValues.Thin;
                worksheet1.Range(1, 1, 1, C).Style.Border.OutsideBorder = XLBorderStyleValues.Thin;
                worksheet1.Range(1, 1, R, C).Style.Font.SetFontSize(9.0).Font.SetFontName("Meiryo UI");
                worksheet1.Range(1, 1, R, C).Style.Alignment.Vertical = XLAlignmentVerticalValues.Center;
                worksheet1.ColumnsUsed().AdjustToContents();

                progressSplash1.ProgressMessage = "ファイル保存中";
                Application.DoEvents();

                try {
                    workbook1.SaveAs(fileName);
                    MessageBox.Show("データインポート用ひな形の出力が完了しました");
                }
                catch {
                    MessageBox.Show("ファイルが使用中等の理由により、保存できませんでした");
                }

                progressSplash1.Close();
                progressSplash1.Dispose();
                this.Activate();
            }
        }




        //別途分析読込用ひな形出力
        private void outputSpecialAnalysisTemplate() {
            SaveFileDialog saveFileDialog1 = new SaveFileDialog();

            string kanrisya = "";
            string syorijou = "";

            if(comboBox1.Enabled) {
                KanrisyaSyorijou item1 = (KanrisyaSyorijou)comboBox1.SelectedItem;
                kanrisya = item1.primaryKey(0);
                syorijou = item1.primaryKey(1);
            }

            string fileName = "別途分析_ひな形";
            string fileNameExtension = "xlsx";

            saveFileDialog1.FileName = fileName + "." + fileNameExtension;
            saveFileDialog1.InitialDirectory = @"%USERPROFILE%\Desktop";
            saveFileDialog1.Filter = "Excel ブック(*.xlsx)|*.xlsx";
            saveFileDialog1.FilterIndex = 1;
            saveFileDialog1.Title = "別途分析読込用ひな形出力";
            saveFileDialog1.RestoreDirectory = true;
            saveFileDialog1.OverwritePrompt = true;
            saveFileDialog1.CheckPathExists = true;

            //ダイアログの表示
            if(saveFileDialog1.ShowDialog() == DialogResult.OK) {
                FormA2ProgressSplash progressSplash1 = new FormA2ProgressSplash();
                progressSplash1.Owner = this;
                progressSplash1.Show();
                progressSplash1.Refresh();

                progressSplash1.ProgressMessage = "ファイル出力中";
                Application.DoEvents();

                fileName = saveFileDialog1.FileName;
                fileNameExtension = fileName.Substring(fileName.Length - 5);

                if(fileNameExtension != ".xlsx") {
                    fileName += ".xlsx";
                }

                XLWorkbook workbook1 = new XLWorkbook();

                IXLWorksheet worksheet1 = workbook1.Worksheets.Add("special_analysis");

                //管理者、処理場、測定日
                int R = 0;
                int C = 1;

                R++;
                worksheet1.Cell(R, C).SetValue("管理者");
                worksheet1.Cell(R, C).SetDataType(XLDataType.Text);
                worksheet1.Cell(R, C).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Left;
                worksheet1.Cell(R, C).Style.Font.Bold = true;
                worksheet1.Cell(R, C).Style.Fill.BackgroundColor = XLColor.LightGray;

                R++;
                worksheet1.Cell(R, C).SetValue("処理場");
                worksheet1.Cell(R, C).SetDataType(XLDataType.Text);
                worksheet1.Cell(R, C).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Left;
                worksheet1.Cell(R, C).Style.Font.Bold = true;
                worksheet1.Cell(R, C).Style.Fill.BackgroundColor = XLColor.LightGray;

                R++;
                worksheet1.Cell(R, C).SetValue("調査日(西暦)");
                worksheet1.Cell(R, C).SetDataType(XLDataType.Text);
                worksheet1.Cell(R, C).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Left;
                worksheet1.Cell(R, C).Style.Font.Bold = true;
                worksheet1.Cell(R, C).Style.Fill.BackgroundColor = XLColor.LightGray;

                R = 0;
                C = 2;

                R++;
                worksheet1.Cell(R, C).SetValue(kanrisya);
                worksheet1.Cell(R, C).SetDataType(XLDataType.Text);
                worksheet1.Cell(R, C).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Left;

                R++;
                worksheet1.Cell(R, C).SetValue(syorijou);
                worksheet1.Cell(R, C).SetDataType(XLDataType.Text);
                worksheet1.Cell(R, C).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Left;

                R++;
                worksheet1.Cell(R, C).SetDataType(XLDataType.DateTime);
                worksheet1.Cell(R, C).Style.NumberFormat.Format = "yyyy/MM/dd";
                worksheet1.Cell(R, C).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Left;

                worksheet1.Range(1, 1, R, C).Style.Border.InsideBorder = XLBorderStyleValues.Thin;
                worksheet1.Range(1, 1, R, C).Style.Border.OutsideBorder = XLBorderStyleValues.Thin;

                //見出し列
                R = 4;
                C = 1;

                R++;
                worksheet1.Cell(R, C).SetValue("項目");
                worksheet1.Cell(R, C).SetDataType(XLDataType.Text);
                worksheet1.Cell(R, C).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
                worksheet1.Cell(R, C).Style.Font.Bold = true;
                worksheet1.Cell(R, C).Style.Fill.BackgroundColor = XLColor.LightGray;

                foreach(ColumnConfig cc in ccSet) {
                    if(cc.HeaderText.Length < 3) {
                        continue;
                    }

                    if(cc.HeaderText.Substring(0, 3) == "別分1") {
                        R++;
                        worksheet1.Cell(R, C).SetValue(cc.HeaderText.Replace("別分1", ""));
                        worksheet1.Cell(R, C).SetDataType(XLDataType.Text);
                        worksheet1.Cell(R, C).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Left;
                        worksheet1.Cell(R, C).Style.Font.Bold = true;
                        worksheet1.Cell(R, C).Style.Fill.BackgroundColor = XLColor.LightGray;
                    }
                }

                //データ列
                for(int i = 1; i <= MaxSizeConfig.maxSpecialAnalysis; i++) {
                    R = 4;
                    C++;

                    R++;
                    worksheet1.Cell(R, C).SetValue("別途分析" + i.ToString());
                    worksheet1.Cell(R, C).SetDataType(XLDataType.Text);
                    worksheet1.Cell(R, C).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
                    worksheet1.Cell(R, C).Style.Font.Bold = true;
                    worksheet1.Cell(R, C).Style.Fill.BackgroundColor = XLColor.LightGray;

                    foreach(ColumnConfig cc in ccSet) {
                        if(cc.HeaderText.Length < 3) {
                            continue;
                        }

                        if(cc.HeaderText.Substring(0, 3) == "別分1") {
                            R++;

                            if(cc.inputType == "ComboBox") {
                                string items = cc.Items;

                                if(items.Substring(0, 1) == ",") {
                                    items = items.Substring(1);
                                }

                                worksheet1.Cell(R, C).DataValidation.List("\"" + items + "\"");
                                worksheet1.Cell(R, C).SetDataType(XLDataType.Text);
                                worksheet1.Cell(R, C).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
                            }
                            else if(cc.inputType == "TextBox") {
                                worksheet1.Cell(R, C).SetDataType(XLDataType.Text);
                                worksheet1.Cell(R, C).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Left;
                            }
                            else {
                                if(cc.Format == "N0") {
                                    worksheet1.Cell(R, C).Style.NumberFormat.Format = "#,##0";
                                }
                                else if(cc.Format == "N1") {
                                    worksheet1.Cell(R, C).Style.NumberFormat.Format = "#,##0.0";
                                }
                                else if(cc.Format == "N2") {
                                    worksheet1.Cell(R, C).Style.NumberFormat.Format = "#,##0.00";
                                }
                                else if(cc.Format == "N3") {
                                    worksheet1.Cell(R, C).Style.NumberFormat.Format = "#,##0.000";
                                }
                                else if(cc.Format == "N4") {
                                    worksheet1.Cell(R, C).Style.NumberFormat.Format = "#,##0.0000";
                                }
                                else if(cc.Format == "N5") {
                                    worksheet1.Cell(R, C).Style.NumberFormat.Format = "#,##0.00000";
                                }

                                worksheet1.Cell(R, C).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Right;
                            }

                            if(cc.Name == "name_exbunseki_1") {
                                using(var con = new SQLiteConnection(DataBaseConfig.ConnectionString)) {
                                    con.Open();

                                    using(var cmd = con.CreateCommand()) {
                                        cmd.CommandText = "SELECT name_exbunseki_" + i.ToString() + " FROM suishitsu_kanri WHERE del_flg IS NULL AND name_exbunseki_" + i.ToString() + " IS NOT NULL AND kanrisya = '" + kanrisya + "' AND syorijou = '" + syorijou + "' ORDER BY sokutei_dt DESC LIMIT 1;";

                                        using(var reader = cmd.ExecuteReader()) {
                                            if(reader.Read()) {
                                                if(!reader.IsDBNull(0)) {
                                                    worksheet1.Cell(R, C).SetValue(reader.GetString(0));
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                //備考列
                R = 4;
                C++;

                R++;
                worksheet1.Cell(R, C).SetValue("記入方式・単位");
                worksheet1.Cell(R, C).SetDataType(XLDataType.Text);
                worksheet1.Cell(R, C).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
                worksheet1.Cell(R, C).Style.Font.Bold = true;
                worksheet1.Cell(R, C).Style.Fill.BackgroundColor = XLColor.LightGray;

                foreach(ColumnConfig cc in ccSet) {
                    if(cc.HeaderText.Length < 3) {
                        continue;
                    }

                    if(cc.HeaderText.Substring(0, 3) == "別分1") {
                        R++;

                        if(cc.inputType == "ComboBox") {
                            string items = cc.Items;

                            if(items.Substring(0, 1) == ",") {
                                items = items.Substring(1);
                            }

                            worksheet1.Cell(R, C).SetValue("選択式(" + items + ")");
                        }
                        else if(cc.inputType == "TextBox") {
                            worksheet1.Cell(R, C).SetValue("文字");
                        }
                        else if(cc.Name == "h_exbunseki_1") {
                            worksheet1.Cell(R, C).SetValue("整数(0-24)");
                        }
                        else if(cc.Name == "m_exbunseki_1") {
                            worksheet1.Cell(R, C).SetValue("整数(0-59)");
                        }
                        else if(cc.Name == "ph_exbunseki_1" || cc.Name == "syuukiidx_exbunseki_1") {
                            worksheet1.Cell(R, C).SetValue("");
                        }
                        else if(cc.unit != "") {
                            worksheet1.Cell(R, C).SetValue(cc.unit);
                        }
                        else {
                            worksheet1.Cell(R, C).SetValue("[mg/L]");
                        }

                        worksheet1.Cell(R, C).SetDataType(XLDataType.Text);
                        worksheet1.Cell(R, C).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Left;
                        worksheet1.Cell(R, C).Style.Fill.BackgroundColor = XLColor.WhiteSmoke;
                    }
                }

                progressSplash1.ProgressMessage = "ワークシート成型中";
                Application.DoEvents();

                worksheet1.Range(5, 1, R, C).Style.Border.InsideBorder = XLBorderStyleValues.Thin;
                worksheet1.Range(5, 1, R, C).Style.Border.OutsideBorder = XLBorderStyleValues.Thin;
                worksheet1.Range(1, 1, R, C).Style.Font.SetFontSize(9.0).Font.SetFontName("Meiryo UI");
                worksheet1.Range(1, 1, R, C).Style.Alignment.Vertical = XLAlignmentVerticalValues.Center;
                worksheet1.ColumnsUsed().AdjustToContents();

                worksheet1.Column(2).Width = 20;
                worksheet1.Column(3).Width = 20;
                worksheet1.Column(4).Width = 20;
                worksheet1.Column(5).Width = 20;

                worksheet1.Cell(R + 1, 1).SetValue("※定量下限値以下は0を記入、測定値なしは空欄としてください");
                worksheet1.Cell(R + 1, 1).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Left;
                worksheet1.Cell(R + 1, 1).Style.Alignment.Vertical = XLAlignmentVerticalValues.Center;
                worksheet1.Cell(R + 1, 1).Style.Font.SetFontSize(9.0).Font.SetFontName("Meiryo UI");

                progressSplash1.ProgressMessage = "ファイル保存中";
                Application.DoEvents();

                try {
                    workbook1.SaveAs(fileName);
                    MessageBox.Show("別途分析読込用ひな形の出力が完了しました");
                }
                catch {
                    MessageBox.Show("ファイルが使用中等の理由により、保存できませんでした");
                }

                progressSplash1.Close();
                progressSplash1.Dispose();
                this.Activate();
            }
        }




        //設定エクスポート
        private void setingExportExcel() {
            using(var con = new SQLiteConnection(DataBaseConfig.ConnectionString)) {
                con.Open();

                using(var cmd1 = con.CreateCommand()) {

                    cmd1.CommandText = "SELECT name FROM sqlite_master WHERE type='table' AND name<>'suishitsu_kanri' AND name<>'sqlite_sequence' AND name<>'uten_judge_uryou_setting';";

                    using(var reader1 = cmd1.ExecuteReader()) {
                        if(reader1.HasRows) {
                            SaveFileDialog saveFileDialog1 = new SaveFileDialog();

                            DateTime now = DateTime.Today;
                            string fileName = "下水設定_" + now.ToString("yyyyMMdd");
                            string fileNameExtension = "xlsx";

                            saveFileDialog1.FileName = fileName + "." + fileNameExtension;
                            saveFileDialog1.InitialDirectory = @"%USERPROFILE%\Desktop";
                            saveFileDialog1.Filter = "Excel ブック(*.xlsx)|*.xlsx";
                            saveFileDialog1.FilterIndex = 1;
                            saveFileDialog1.Title = "設定エクスポート(エクセル形式)";
                            saveFileDialog1.RestoreDirectory = true;
                            saveFileDialog1.OverwritePrompt = true;
                            saveFileDialog1.CheckPathExists = true;

                            //ダイアログの表示
                            if(saveFileDialog1.ShowDialog() == DialogResult.OK) {
                                FormA2ProgressSplash progressSplash1 = new FormA2ProgressSplash();
                                progressSplash1.Owner = this;
                                progressSplash1.Show();
                                progressSplash1.Refresh();

                                progressSplash1.ProgressMessage = "ファイル出力中";
                                Application.DoEvents();

                                fileName = saveFileDialog1.FileName;
                                fileNameExtension = fileName.Substring(fileName.Length - 5);

                                if(fileNameExtension != ".xlsx") {
                                    fileName += ".xlsx";
                                }

                                XLWorkbook workbook1 = new XLWorkbook();

                                while(reader1.Read()) {
                                    string tableName = reader1.GetString(0);
                                    IXLWorksheet worksheet = workbook1.Worksheets.Add(tableName);

                                    int R = 1;
                                    int C = 0;
                                    string columnNames = "";

                                    //見出し行
                                    using(var cmd2 = con.CreateCommand()) {
                                        cmd2.CommandText = "PRAGMA TABLE_INFO(" + tableName + ");";

                                        using(var reader2 = cmd2.ExecuteReader()) {
                                            while(reader2.Read()) {
                                                C++;    
                                                worksheet.Cell(R, C).Value = reader2.GetString(1);

                                                if(C > 1) {
                                                    columnNames += ", ";
                                                }

                                                columnNames += reader2.GetString(1);
                                            }
                                        }
                                    }

                                    int columnNo = C;

                                    //データ行
                                    using(var cmd3 = con.CreateCommand()) {
                                        cmd3.CommandText = "SELECT " + columnNames + " FROM " + tableName + "; ";

                                        using(var reader3 = cmd3.ExecuteReader()) {
                                            while(reader3.Read()) {
                                                R++;
                                                for(C = 1; C <= columnNo; C++) {
                                                    worksheet.Cell(R, C).Value = reader3.GetValue(C - 1);
                                                }
                                            }
                                        }
                                    }

                                    worksheet.Columns().AdjustToContents();
                                }

                                progressSplash1.ProgressMessage = "ファイル保存中";
                                Application.DoEvents();

                                try {
                                    workbook1.SaveAs(fileName);
                                    MessageBox.Show("設定のエクスポートが完了しました");
                                }
                                catch {
                                    MessageBox.Show("ファイルが使用中等の理由により、保存できませんでした");
                                }

                                progressSplash1.Close();
                                progressSplash1.Dispose();
                                this.Activate();
                            }
                        }
                        else {
                            MessageBox.Show("設定データベースがありません");
                        }
                    }
                }
            }
		}




        //データ項目一覧出力
        private void columnConfigExportExcel() {
            SaveFileDialog saveFileDialog1 = new SaveFileDialog();

            string fileName = "下水データ管理システムデータ項目一覧";
            string fileNameExtension = "xlsx";

            saveFileDialog1.FileName = fileName + "." + fileNameExtension;
            saveFileDialog1.InitialDirectory = @"%USERPROFILE%\Desktop";
            saveFileDialog1.Filter = "Excel ブック(*.xlsx)|*.xlsx";
            saveFileDialog1.FilterIndex = 1;
            saveFileDialog1.Title = "データ項目一覧出力";
            saveFileDialog1.RestoreDirectory = true;
            saveFileDialog1.OverwritePrompt = true;
            saveFileDialog1.CheckPathExists = true;

            //ダイアログの表示
            if(saveFileDialog1.ShowDialog() == DialogResult.OK) {
                FormA2ProgressSplash progressSplash1 = new FormA2ProgressSplash();
                progressSplash1.Owner = this;
                progressSplash1.Show();
                progressSplash1.Refresh();

                progressSplash1.ProgressMessage = "ファイル出力中";
                Application.DoEvents();

                fileName = saveFileDialog1.FileName;
                fileNameExtension = fileName.Substring(fileName.Length - 5);

                if(fileNameExtension != ".xlsx") {
                    fileName += ".xlsx";
                }

                XLWorkbook workbook1 = new XLWorkbook();
                IXLWorksheet worksheet1 = workbook1.Worksheets.Add("Sheet1");

                //見出し行
                int R = 1;
                int C = 0;

                C++;
                worksheet1.Cell(R, C).SetValue("データ項目名");

                C++;
                worksheet1.Cell(R, C).SetValue("DB列名");

                C++;
                worksheet1.Cell(R, C).SetValue("単位");

                C++;
                worksheet1.Cell(R, C).SetValue("データ形式");

                C++;
                worksheet1.Cell(R, C).SetValue("静的");

                C++;
                worksheet1.Cell(R, C).SetValue("計算値");

                C++;
                worksheet1.Cell(R, C).SetValue("計算源");

                C++;
                worksheet1.Cell(R, C).SetValue("入力上限");

                C++;
                worksheet1.Cell(R, C).SetValue("入力下限");

                C++;
                worksheet1.Cell(R, C).SetValue("警告上限");

                C++;
                worksheet1.Cell(R, C).SetValue("警告下限");

                C++;
                worksheet1.Cell(R, C).SetValue("計算式または選択肢");

                worksheet1.Range(1, 1, R, C).Style.Fill.BackgroundColor = XLColor.LightGray;

                int maxC = C;

                //データ行
                int i = 0;
                foreach(ColumnConfig cc in ccSet) {
                    i++;

                    if(cc.Name == "id" || cc.Name == "del_flg" || cc.Name == "input_dt") {
                        continue;
                    }

                    if(tabTopColumnNumber.Contains(i - 1)) {
                        R++;
                        C = 1;
                        worksheet1.Cell(R, C).SetValue("【" + InputTab.title[tabTopColumnNumber.IndexOf(i - 1)] + "】");
                        worksheet1.Cell(R, C).Style.Fill.BackgroundColor = XLColor.Orange;
                    }

                    R++;
                    C = 0;

                    C++;
                    worksheet1.Cell(R, C).SetValue(cc.HeaderText);

                    C++;
                    worksheet1.Cell(R, C).SetValue(cc.Name);

                    C++;
                    worksheet1.Cell(R, C).SetValue(cc.unit);

                    C++;
                    if(cc.inputType == "TextBox") {
                        worksheet1.Cell(R, C).SetValue("テキスト");
                    }
                    else if(cc.inputType== "ComboBox") {
                        worksheet1.Cell(R, C).SetValue("選択式");
                    }
                    else if(cc.inputType == "DateTimePicker") {
                        worksheet1.Cell(R, C).SetValue(cc.Format);
                    }
                    else if(cc.inputType == "NumericUpDown" || cc.calculatedDecimal) {
                        if(cc.Format == "N0") {
                            worksheet1.Cell(R, C).SetValue("N");
                        }
                        else if(cc.Format == "N1") {
                            worksheet1.Cell(R, C).SetValue("N.0");
                        }
                        else if(cc.Format == "N2") {
                            worksheet1.Cell(R, C).SetValue("N.00");
                        }
                        else if(cc.Format == "N3") {
                            worksheet1.Cell(R, C).SetValue("N.000");
                        }
                        else if(cc.Format == "N4") {
                            worksheet1.Cell(R, C).SetValue("N.0000");
                        }
                        else if(cc.Format == "N5") {
                            worksheet1.Cell(R, C).SetValue("N.00000");
                        }
                    }
                    else {
                        worksheet1.Cell(R, C).SetValue(cc.Format);
                    }

                    C++;
                    if(cc.statical) {
                        worksheet1.Cell(R, C).SetValue("○");
                        worksheet1.Cell(R, C).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
                    }

                    C++;
                    if(cc.calculatedDecimal || cc.calculatedString) {
                        worksheet1.Cell(R, C).SetValue("○");
                        worksheet1.Cell(R, C).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
                    }

                    C++;
                    if(cc.calculateSource) {
                        worksheet1.Cell(R, C).SetValue("○");
                        worksheet1.Cell(R, C).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
                    }

                    C++;
                    if(cc.inputType == "NumericUpDown") {
                        worksheet1.Cell(R, C).SetValue(cc.Maximum);
                    }

                    C++;
                    if(cc.inputType == "NumericUpDown") {
                        worksheet1.Cell(R, C).SetValue(cc.Minimum);
                    }

                    C++;
                    if(cc.inputType == "NumericUpDown") {
                        if(!string.IsNullOrEmpty(cc.validMax.ToString())) {
                            worksheet1.Cell(R, C).SetValue(cc.validMax);
                        }
                    }

                    C++;
                    if(cc.inputType == "NumericUpDown") {
                        if(!string.IsNullOrEmpty(cc.validMin.ToString())) {
                            worksheet1.Cell(R, C).SetValue(cc.validMin);
                        }
                    }

                    C++;
                    if(cc.inputType == "ComboBox") {
                        worksheet1.Cell(R, C).SetValue(cc.Items);
                    }
                    else if(cc.calculatedDecimal || cc.calculatedString) {
                        worksheet1.Cell(R, C).SetValue(cc.calculateFormula);
                    }

                    if(cc.calculatedDecimal || cc.calculatedString) {
                        worksheet1.Range(R,1,R,C).Style.Fill.BackgroundColor = XLColor.LightSteelBlue;
                    }
                }

                progressSplash1.ProgressMessage = "ワークシート成型中";
                Application.DoEvents();

                worksheet1.SheetView.FreezeRows(1);
                worksheet1.Range(1, 1, R, C).Style.Border.InsideBorder = XLBorderStyleValues.Thin;
                worksheet1.Range(1, 1, R, C).Style.Border.OutsideBorder = XLBorderStyleValues.Thin;
                worksheet1.Range(1, 1, R, C).Style.Font.SetFontSize(9.0).Font.SetFontName("Meiryo UI");
                worksheet1.Range(1, 1, R, C).Style.Alignment.Vertical = XLAlignmentVerticalValues.Center;
                worksheet1.ColumnsUsed().AdjustToContents();

                progressSplash1.ProgressMessage = "ファイル保存中";
                Application.DoEvents();

                try {
                    workbook1.SaveAs(fileName);
                    MessageBox.Show("データ項目一覧の出力が完了しました");
                }
                catch {
                    MessageBox.Show("ファイルが使用中等の理由により、保存できませんでした");
                }

                progressSplash1.Close();
                progressSplash1.Dispose();
                this.Activate();
            }
        }

        


        #region ボタン・メニューバークリックイベント

        //追加ボタンクリックイベント
        private void button2_Click(object sender, EventArgs e) {
            suishitsu_kanriInsert();
        }




        //帳票印刷ボタンクリックイベント
        private void button3_Click(object sender, EventArgs e) {
            outputPrintForm();
        }




        //グラフ印刷ボタンクリックイベント
        private void button4_Click(object sender, EventArgs e) {
            outputGraph();
        }




        //月報出力ボタンクリックイベント
        private void button5_Click(object sender, EventArgs e) {
            outputMonthlyReport();
        }




        //メニューバーのデータインポートクリックイベント
        private void ToolStripMenuItemInpExcel_Click(object sender, EventArgs e) {
            KanrisyaSyorijou item1 = (KanrisyaSyorijou)comboBox1.SelectedItem;
            string kanrisya = "";
            string syorijou = "";

            if(item1 != null) {
                kanrisya = item1.primaryKey(0);
                syorijou = item1.primaryKey(1);
            }

            SelectableMonth item2 = (SelectableMonth)comboBox2.SelectedItem;
            int cDtY = -1;
            int cDtM = -1;

            if(item2 != null) {
                cDtY = item2.primaryKey(0);
                cDtM = item2.primaryKey(1);
            }

            var win = new Form6ImportData();
            win.Owner = this;
            win.WindowState = this.WindowState;
            win.Height = this.Size.Height;
            win.Width = this.Size.Width;
            win.StartPosition = FormStartPosition.CenterParent;
            win.ShowDialog();

            //フォームクローズ後の処理
            if(win.finInport) {
                //データ再表示
                dataSelectConstruction(kanrisya, syorijou);

                monthSelectConstruction(cDtY, cDtM);

                suishitsu_kanriSelect();
            }

            win.Dispose();
        }




        //メニューバーのデータエクスポートクリックイベント
        private void ToolStripMenuItemExpExcel_Click(object sender, EventArgs e) {
            dataExportExcel();
        }




        //メニューバーのデータインポート用ひな形出力クリックイベント
        private void ToolStripMenuItemOutputDataTemplate_Click(object sender, EventArgs e) {
            outputDataTemplate();
        }




        //メニューバーのデータファイルマージクリックイベント
        private void ToolStripMenuItemDataFileMerge_Click(object sender, EventArgs e) {
            KanrisyaSyorijou item1 = (KanrisyaSyorijou)comboBox1.SelectedItem;
            string kanrisya = "";
            string syorijou = "";

            if(item1 != null) {
                kanrisya = item1.primaryKey(0);
                syorijou = item1.primaryKey(1);
            }

            SelectableMonth item2 = (SelectableMonth)comboBox2.SelectedItem;
            int cDtY = -1;
            int cDtM = -1;

            if(item2 != null) {
                cDtY = item2.primaryKey(0);
                cDtM = item2.primaryKey(1);
            }

            var win = new FormB1MergeData();
            win.Owner = this;
            win.WindowState = this.WindowState;
            win.Height = this.Size.Height;
            win.Width = this.Size.Width;
            win.StartPosition = FormStartPosition.CenterParent;
            win.ShowDialog();

            //フォームクローズ後の処理
            if(win.finInport) {
                //データ再表示
                dataSelectConstruction(kanrisya, syorijou);

                monthSelectConstruction(cDtY, cDtM);

                suishitsu_kanriSelect();
            }

            win.Dispose();
        }




        //メニューバーの別途分析ファイル読込クリックイベント
        private void ToolStripMenuItemSpecialAnalysisMerge_Click(object sender, EventArgs e) {
            KanrisyaSyorijou item1 = (KanrisyaSyorijou)comboBox1.SelectedItem;
            string kanrisya = "";
            string syorijou = "";

            if(item1 != null) {
                kanrisya = item1.primaryKey(0);
                syorijou = item1.primaryKey(1);
            }

            SelectableMonth item2 = (SelectableMonth)comboBox2.SelectedItem;
            int cDtY = -1;
            int cDtM = -1;

            if(item2 != null) {
                cDtY = item2.primaryKey(0);
                cDtM = item2.primaryKey(1);
            }

            var win = new FormC1MergeSpecialAnalysis();
            win.Owner = this;
            win.WindowState = this.WindowState;
            win.Height = this.Size.Height;
            win.Width = this.Size.Width;
            win.StartPosition = FormStartPosition.CenterParent;
            win.ShowDialog();

            //フォームクローズ後の処理
            if(win.finInport) {
                //データ再表示
                dataSelectConstruction(kanrisya, syorijou);

                monthSelectConstruction(cDtY, cDtM);

                suishitsu_kanriSelect();
            }

            win.Dispose();
        }




        //メニューバーの別途分析読込用ひな形出力クリックイベント
        private void ToolStripMenuItemOutputSpecialAnalysisTemplate_Click(object sender, EventArgs e) {
            outputSpecialAnalysisTemplate();
        }
        
        
        
        
        //メニューバーの終了クリックイベント
        private void ToolStripMenuItemEnd_Click(object sender, EventArgs e) {
            this.Close();
        }




        //メニューバーの編集オープンイベント
        private void ToolStripMenuItemEdit_DropDownOpened(object sender, EventArgs e) {
            if(dataGridView1.SelectedRows.Count < 1) {
                ToolStripMenuItemUpdate.Enabled = false;
                ToolStripMenuItemDelete.Enabled = false;
            }
            else if(dataGridView1.SelectedRows.Count == 1) {
                ToolStripMenuItemUpdate.Enabled = true;
                ToolStripMenuItemDelete.Enabled = true;
            }
            else {
                ToolStripMenuItemUpdate.Enabled = false;
                ToolStripMenuItemDelete.Enabled = true;
            }

            using(var con = new SQLiteConnection(DataBaseConfig.ConnectionString)) {
                con.Open();

                using(var cmd = con.CreateCommand()) {
                    cmd.CommandText = "SELECT COUNT(*) FROM suishitsu_kanri WHERE del_flg = 1;";

                    using(var reader = cmd.ExecuteReader()) {
                        if(reader.Read()) {
                            if(reader.GetInt32(0) > 0) {
                                //削除フラグ付きレコードあり
                                ToolStripMenuItemUndo.Enabled = true;
                            }
                            else {
                                //削除フラグ付きレコードなし
                                ToolStripMenuItemUndo.Enabled = false;
                            }
                        }
                    }
                }

                con.Close();
            }
        }




        //メニューバーの追加クリックイベント
        private void ToolStripMenuItemInsert_Click(object sender, EventArgs e) {
            suishitsu_kanriInsert();
        }




        //メニューバーの修正クリックイベント
        private void ToolStripMenuItemUpdate_Click(object sender, EventArgs e) {
            suishitsu_kanriUpdate(dataGridView1.SelectedRows[0].Index);
        }




        //メニューバーの削除クリックイベント
        private void ToolStripMenuItemDelete_Click(object sender, EventArgs e) {
            suishitsu_kanriDelete();
        }




        //メニューバーの直前に削除したデータを元に戻すクリックイベント
        private void ToolStripMenuItemUndo_Click(object sender, EventArgs e) {
            if(MessageBox.Show("直前に削除したデータを元に戻してよろしいですか", "", MessageBoxButtons.OKCancel) == DialogResult.Cancel) {
                return;
            }

            KanrisyaSyorijou item1 = (KanrisyaSyorijou)comboBox1.SelectedItem;
            string kanrisya = "";
            string syorijou = "";

            if(item1 != null) {
                kanrisya = item1.primaryKey(0);
                syorijou = item1.primaryKey(1);
            }

            SelectableMonth item2 = (SelectableMonth)comboBox2.SelectedItem;
            int cDtY = -1;
            int cDtM = -1;

            if(item2 != null) {
                cDtY = item2.primaryKey(0);
                cDtM = item2.primaryKey(1);
            }

            int topLineRow = 0;

            if(cDtY > -1 && cDtM > -1) {
                topLineRow = dataGridView1.FirstDisplayedScrollingRowIndex;
            }

            using(var con = new SQLiteConnection(DataBaseConfig.ConnectionString)) {
                con.Open();

                try {
                    //削除フラグON
                    using(var cmd = con.CreateCommand()) {
                        cmd.CommandText = "UPDATE suishitsu_kanri SET del_flg = null WHERE del_flg = 1;";
                        cmd.ExecuteNonQuery();
                    }
                }
                catch(Exception ex) {
                    MessageBox.Show(ex.Message);
                    return;
                }

                con.Close();
            }

            FormA2ProgressSplash progressSplash1 = new FormA2ProgressSplash();
            progressSplash1.Owner = this;
            progressSplash1.Show();
            progressSplash1.Refresh();

            progressSplash1.ProgressMessage = "晴天日判定中";
            Application.DoEvents();

            //対象処理場全件の晴天日再判定
            FunctionForDatabase.judgeSeitenUpdateDB(kanrisya, syorijou);

            progressSplash1.Close();
            progressSplash1.Dispose();
            this.Activate();

            //データ再表示
            dataSelectConstruction(kanrisya, syorijou);

            monthSelectConstruction(cDtY, cDtM);

            suishitsu_kanriSelect();

            //行がある場合、元の位置にスクロール
            if(dataGridView1.FirstDisplayedScrollingRowIndex >= 0) {
                if(topLineRow < (dataGridView1.Rows.Count - 1) && topLineRow > 0) {
                    dataGridView1.FirstDisplayedScrollingRowIndex = topLineRow;
                }
                else if(dataGridView1.Rows.Count > 0) {
                    dataGridView1.FirstDisplayedScrollingRowIndex = dataGridView1.Rows.Count - 1;
                }

                dataGridView1.Rows[0].Selected = false;
            }
        }




        //メニューバーの帳票印刷クリックイベント
        private void ToolStripMenuItemFormPrint_Click(object sender, EventArgs e) {
            outputPrintForm();
        }




        //メニューバーのグラフ印刷クリックイベント
        private void ToolStripMenuItemGraphPrint_Click(object sender, EventArgs e) {
            outputGraph();
        }

        
        
        
        //メニューバーの月報出力クリックイベント
        private void ToolStripMenuItemOutputMonthlyReport_Click(object sender, EventArgs e) {
            outputMonthlyReport();
        }




        //メニューバーの年報出力クリックイベント
        private void ToolStripMenuItemOutputAnnualReport_Click(object sender, EventArgs e) {
            outputAnnualReport();
        }




        //メニューバーの四半期毎集計データ出力クリックイベント
        private void ToolStripMenuItemOutputQuarterData_Click(object sender, EventArgs e) {
            outputQuarterData();
        }




        //メニューバーの四半期毎集計データ出力クリックイベント
        private void ToolStripMenuItemOutputYearData_Click(object sender, EventArgs e) {
            outputYearData();
        }




        //メニューバーの設定インポートクリックイベント
        private void ToolStripMenuItemSettingInport_Click(object sender, EventArgs e) {
            var win = new Form9InportSetting();
            win.Owner = this;
            win.StartPosition = FormStartPosition.CenterParent;
            win.ShowDialog();

            //フォームクローズ後の処理
            if(win.finInport) {
                FormA2ProgressSplash progressSplash1 = new FormA2ProgressSplash();
                progressSplash1.Owner = this;
                progressSplash1.Show();
                progressSplash1.Refresh();

                dataGridViewColumnSetting(null, progressSplash1);

                progressSplash1.Close();
                progressSplash1.Dispose();
                this.Activate();
            }

            win.Dispose();
        }




        //メニューバーの設定エクスポートクリックイベント
        private void ToolStripMenuItemSettingExport_Click(object sender, EventArgs e) {
            setingExportExcel();
        }
        
        
        
        
        //メニューバーの表示データ設定クリックイベント
        private void ToolStripMenuItemSettingColumn_Click(object sender, EventArgs e) {
            win5.WindowState = FormWindowState.Normal;
            win5.preMake = false;
            win5.changed = false;
            win5.ShowDialog();

            if(win5.changed) {
                FormA2ProgressSplash progressSplash1 = new FormA2ProgressSplash();
                progressSplash1.Owner = this;
                progressSplash1.Show();
                progressSplash1.Refresh();

                dataGridViewColumnSetting(null, progressSplash1);

                progressSplash1.Close();
                progressSplash1.Dispose();
                this.Activate();
            }
        }




        //メニューバーの帳票印刷列設定クリックイベント
        private void ToolStripMenuItemSettingPrintForm_Click(object sender, EventArgs e) {
            ToolStripMenuItem sendMenu = (ToolStripMenuItem)sender;

            string printFromNoSTR = Regex.Replace(sendMenu.Text, @"\(.*\)", "");
            printFromNoSTR = Regex.Replace(printFromNoSTR, "帳票", "");

            int printFormNo = int.Parse(printFromNoSTR);

            win7.printFormNo = printFormNo;
            win7.WindowState = FormWindowState.Normal;
            win7.preMake = false;
            win7.ShowDialog();
        }




        //メニューバーの晴天日判定雨量設定クリックイベント
        private void ToolStripMenuItemSettingSeitenJudge_Click(object sender, EventArgs e) {
            KanrisyaSyorijou item1 = (KanrisyaSyorijou)comboBox1.SelectedItem;
            string kanrisya = "";
            string syorijou = "";

            int topLineRow = dataGridView1.FirstDisplayedScrollingRowIndex;

            if(topLineRow < 0) {
                topLineRow = 0;
            }

            int selectedRowIndex = 0;

            if(dataGridView1.RowCount > 0 && dataGridView1.SelectedRows.Count > 0) {
                selectedRowIndex = dataGridView1.SelectedRows[0].Index;
            }

            if(item1 != null) {
                kanrisya = item1.primaryKey(0);
                syorijou = item1.primaryKey(1);
            }

            var win = new Form8SettingSeitenJudge();
            win.Owner = this;
            win.kanrisya = kanrisya;
            win.syorijou = syorijou;
            win.StartPosition = FormStartPosition.CenterParent;
            win.ShowDialog();
            win.Dispose();

            //フォームクローズ後の処理
            if(win.changed) {
                FormA2ProgressSplash progressSplash1 = new FormA2ProgressSplash();
                progressSplash1.Owner = this;
                progressSplash1.Show();
                progressSplash1.Refresh();

                progressSplash1.ProgressMessage = "晴天日判定中";
                Application.DoEvents();

                //対象処理場全件の晴天日再判定
                FunctionForDatabase.judgeSeitenUpdateDB(kanrisya, syorijou);
                
                progressSplash1.Close();
                progressSplash1.Dispose();
                this.Activate();

                suishitsu_kanriSelect();

                if(dataGridView1.FirstDisplayedScrollingRowIndex >= 0) {
                    dataGridView1.FirstDisplayedScrollingRowIndex = topLineRow;
                    dataGridView1.Rows[0].Selected = false;

                    if(dataGridView1.RowCount > 0) {
                        dataGridView1.Rows[selectedRowIndex].Selected = true;
                    }
                }
            }
        }




        //メニューバーのヘルプの表示クリックイベント
        private void ヘルプHToolStripMenuItem_Click(object sender, EventArgs e) {
            string appDirectory = AppDomain.CurrentDomain.BaseDirectory.TrimEnd('\\');

            try {
                System.Diagnostics.Process.Start(appDirectory + "\\Help\\help.html");
            }
            catch {
                MessageBox.Show("ヘルプファイルが存在しません");
            }
        }

        
        
        
        //メニューバーのデータ項目一覧出力クリックイベント
        private void ToolStripMenuItemColumns_Click(object sender, EventArgs e) {
            columnConfigExportExcel();
        }
        
        

        
        //メニューバーのこのソフトについてクリックイベント
        private void ToolStripMenuItemAbout_Click(object sender, EventArgs e) {
            var win = new Form4About();
            win.Owner = this;
            win.StartPosition = FormStartPosition.CenterParent;
            win.ShowDialog();
            win.Dispose();
        }

        #endregion

    }
}
