// 下水データ管理システム
// 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 System;
using System.Collections.Generic;
using System.Data.SQLite;
using System.Drawing;
using System.Windows.Forms;

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


        TabControl tabControl1 = new TabControlEx();

        List<ColumnConfig> ccSet = ColumnsConfigSet.getSet;
        List<string> inputTabTitle = InputTab.title;

        int place = 4;
        Panel[] putPlace;
        int[] placeCount;
        DateTime currentDate;
        bool initializing;
        int id = -1;

        Color controlNotEnableBC = Color.WhiteSmoke;
        Color validationOK = Color.FromArgb(225, 225, 225);
        Color validationNG = Color.FromArgb(255, 0, 0);
        Color noChanged = Color.Black;
        Color hasChanged = Color.Red;
        Color noChanged2V = Color.Gray;
        Color hasChanged2V = Color.Red;
        Color lockedTB = Color.FromArgb(162, 192, 242);
        Color unlockedTB = Color.White;

        public DataGridView dgv { get; set; }
        public string kanrisya { get; set; }
        public string syorijou { get; set; }
        public int curRow { get; set; }
        public bool newRecord { get; set; }
        public bool dbChanged { get; set; }
        public DateTime sokutei_dt { get; set; }
        public bool preMake { get; set; }
        public bool formChanged { get; set; }

        public FormA1OpeningSplash winSplash { get; set; }




        //ロード時イベント
        private void Form2InputPreMake_Load(object sender, EventArgs e) {
            this.SuspendLayout();

            if(preMake) {
                //プログラム起動時のフォーム事前生成
                this.Visible = false;

                makeInputForm();

                this.Close();
            }
            else {
                formChanged = false;
                initializing = true;

                //追加・変更時のフォーム状態セット
                setInputForm();

                if(newRecord) {
                    this.Text = "データ追加";
                    label1.Text = "新規にデータを追加します";
                    button1.Text = "追加する";
                }
                else {
                    this.Text = "データ修正";
                    label1.Text = "既存のデータを修正します";
                    button1.Text = "変更する";
                }

                allInputBoxValidation();
                dassuikiTypeSet();

                initializing = false;

                calculate2ndValue(true);
                presetValueChangedSetting();

                dbChanged = false;
                tabControl1.SelectedIndex = 0;
                tabControl1.Size = new Size(992, 551);
                this.ActiveControl = button2;
            }

            this.ResumeLayout();
        }




        //入力フォーム生成
        private void makeInputForm() {
            //パネル生成
            putPlace = new Panel[(inputTabTitle.Count + 1) * 10 + place];
            placeCount = new int[(inputTabTitle.Count + 1) * 10 + place];

            tabControl1.Anchor = (AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right);
            tabControl1.Location = new Point(9, 42);
            tabControl1.Size = new Size(992, 511);
            tabControl1.SizeMode = TabSizeMode.Fixed;
            tabControl1.Multiline = true;
            tabControl1.ItemSize = new Size(73, 19);
            tabControl1.Appearance = TabAppearance.FlatButtons;

            this.Controls.Add(tabControl1);

            for(int i = 0; i < inputTabTitle.Count; i++) {
                for(int j = 0; j < 4; j++) {
                    Panel newPanel = new Panel();
                    newPanel.AutoSize = true;
                    newPanel.Location = new Point(j * 242 + 5, 5);
                    newPanel.Name = "panel" + (i + 1).ToString() + (j + 1).ToString();
                    newPanel.BorderStyle = BorderStyle.None;

                    putPlace[(i + 1) * 10 + j + 1] = newPanel;
                    placeCount[(i + 1) * 10 + j + 1] = 0;
                }
            }

            //コントロール配置
            int pitchY = 27;
            int offsetY = 8;
            int ccNo = 0;
            decimal stepPer100 = 100M / ccSet.Count;
            decimal setpIntegrate = 0;

            foreach(ColumnConfig cc in ccSet) {
                ccNo++;
                setpIntegrate += stepPer100;

                if(setpIntegrate >= 10) {
                    winSplash.ProgressMessage = "データ入力フォーム生成中（" + (Math.Round((decimal)ccNo / ccSet.Count * 10M, 0) * 10).ToString() + "%）";
                    Application.DoEvents();
                    setpIntegrate = 0;
                }

                if(cc.Name != "id" && cc.Name != "del_flg" && cc.Name != "input_dt" && cc.Name != "seiten") {
                    if(cc.calculatedDecimal || cc.calculatedString) {
                        Label valueLabel = new Label();
                        valueLabel.Name = cc.Name;
                        valueLabel.Size = new Size(70, 21);
                        valueLabel.Location = new Point(159, placeCount[cc.putPlaceNo] * pitchY + offsetY + 1);
                        valueLabel.TextAlign = ContentAlignment.MiddleRight;

                        putPlace[cc.putPlaceNo].Controls.Add(valueLabel);

                        Label borderLabel = new Label();
                        borderLabel.Name = "bl_" + cc.Name;
                        borderLabel.Size = new Size(72, 23);
                        borderLabel.Location = new Point(valueLabel.Location.X - 1, valueLabel.Location.Y - 1);
                        borderLabel.BorderStyle = BorderStyle.FixedSingle;
                        borderLabel.BackColor = Color.WhiteSmoke;

                        putPlace[cc.putPlaceNo].Controls.Add(borderLabel);
                    }
                    else if(cc.inputType == "TextBox") {
                        TextBox newTextBox = new TextBox();
                        newTextBox.Name = cc.Name;
                        newTextBox.Font = new Font("Meiryo UI", 9F, FontStyle.Regular, GraphicsUnit.Point, ((byte)(128)));
                        newTextBox.Size = new Size(128, 25);
                        newTextBox.Location = new Point(97, placeCount[cc.putPlaceNo] * pitchY + offsetY + 3);
                        newTextBox.BorderStyle = BorderStyle.None;
                        newTextBox.BackColor = Color.White;

                        if(cc.calculateSource) {
                            newTextBox.TextChanged += new EventHandler((sender, args) => calculate2ndValueStart(cc, sender, args));
                        }
                        else {
                            newTextBox.TextChanged += new EventHandler((sender, args) => noCalculate2ndValueStart(cc,sender, args));
                        }

                        if(cc.statical || cc.Name == "kanrisya" || cc.Name == "syorijou") {
                            newTextBox.TabStop = false;
                            newTextBox.Click += new EventHandler(staticalTextBoxVisit);
                            newTextBox.Leave += new EventHandler(staticalTextBoxExit);
                        }

                        if(cc.Name == "kanrisya" || cc.Name == "syorijou") {
                            newTextBox.TextChanged += new EventHandler(sokutei_dtValidation);
                        }

                        Label newValidationLabel = new Label();
                        newValidationLabel.Name = "vl_" + cc.Name;
                        newValidationLabel.Size = new Size(6, 21);
                        newValidationLabel.Location = new Point(223, placeCount[cc.putPlaceNo] * pitchY + offsetY + 1);
                        newValidationLabel.Padding = new Padding(0, 0, 0, 0);
                        newValidationLabel.BackColor = validationOK;
                        newValidationLabel.Text = "";
                        putPlace[cc.putPlaceNo].Controls.Add(newValidationLabel);

                        if(cc.validNull) {
                            newTextBox.TextChanged += new EventHandler((sender, args) => textBoxValidation(newValidationLabel, sender, args));
                        }

                        putPlace[cc.putPlaceNo].Controls.Add(newTextBox);

                        Label borderLabel = new Label();
                        borderLabel.Name = "bl_" + cc.Name;
                        borderLabel.Size = new Size(135, 23);
                        borderLabel.Location = new Point(newTextBox.Location.X - 2, newTextBox.Location.Y - 3);
                        borderLabel.BorderStyle = BorderStyle.FixedSingle;
                        borderLabel.BackColor = Color.White;
                        putPlace[cc.putPlaceNo].Controls.Add(borderLabel);
                    }
                    else if(cc.inputType == "DateTimePicker") {
                        DateTimePicker newDateTimePicker = new DateTimePicker();
                        newDateTimePicker.Name = cc.Name;
                        newDateTimePicker.Font = new Font("Meiryo UI", 9F, FontStyle.Regular, GraphicsUnit.Point, ((byte)(128)));
                        newDateTimePicker.Size = new Size(134, 25);
                        newDateTimePicker.Location = new Point(90, placeCount[cc.putPlaceNo] * pitchY + offsetY);
                        newDateTimePicker.Format = DateTimePickerFormat.Custom;
                        newDateTimePicker.CustomFormat = "yyyy年M月d日";

                        if(cc.calculateSource) {
                            newDateTimePicker.ValueChanged += new EventHandler((sender, args) => calculate2ndValueStart(cc, sender, args));
                        }
                        else {
                            newDateTimePicker.ValueChanged += new EventHandler((sender, args) => noCalculate2ndValueStart(cc, sender, args));
                        }

                        Label newValidationLabel = new Label();
                        newValidationLabel.Name = "vl_" + cc.Name;
                        newValidationLabel.Size = new Size(6, 21);
                        newValidationLabel.Location = new Point(223, placeCount[cc.putPlaceNo] * pitchY + offsetY + 1);
                        newValidationLabel.Padding = new Padding(0, 0, 0, 0);
                        newValidationLabel.BackColor = validationOK;
                        newValidationLabel.Text = "";
                        putPlace[cc.putPlaceNo].Controls.Add(newValidationLabel);

                        if(cc.Name == "sokutei_dt") {
                            newDateTimePicker.ValueChanged += new EventHandler(sokutei_dtValidation);
                        }

                        putPlace[cc.putPlaceNo].Controls.Add(newDateTimePicker);

                        Label borderLabel = new Label();
                        borderLabel.Name = "bl_" + cc.Name;
                        borderLabel.Size = new Size(140, 23);
                        borderLabel.Location = new Point(newDateTimePicker.Location.X, newDateTimePicker.Location.Y);
                        ;
                        borderLabel.BorderStyle = BorderStyle.FixedSingle;
                        borderLabel.BackColor = Color.White;
                        putPlace[cc.putPlaceNo].Controls.Add(borderLabel);
                    }
                    else if(cc.inputType == "ComboBox") {
                        ComboBoxEx newComboBox = new ComboBoxEx();
                        newComboBox.Name = cc.Name;
                        newComboBox.Font = new Font("Meiryo UI", 9F, FontStyle.Regular, GraphicsUnit.Point, ((byte)(128)));
                        newComboBox.Size = new Size(90, 23);
                        newComboBox.Location = new Point(139, placeCount[cc.putPlaceNo] * pitchY + offsetY);
                        newComboBox.FlatStyle = FlatStyle.Flat;
                        newComboBox.BackColor = Color.White;
                        newComboBox.DropDownStyle = ComboBoxStyle.DropDownList;
                        newComboBox.Items.AddRange(cc.Items.Split(','));
                        newComboBox.FormattingEnabled = true;
                        newComboBox.SelectedIndex = 0;

                        if(cc.calculateSource) {
                            newComboBox.SelectedValueChanged += new EventHandler((sender, args) => calculate2ndValueStart(cc, sender, args));
                        }
                        else {
                            newComboBox.SelectedValueChanged += new EventHandler((sender, args) => noCalculate2ndValueStart(cc, sender, args));
                        }

                        putPlace[cc.putPlaceNo].Controls.Add(newComboBox);

                        Label borderLabel = new Label();
                        borderLabel.Name = "bl_" + cc.Name;
                        borderLabel.Size = new Size(92, 25);
                        borderLabel.Location = new Point(newComboBox.Location.X - 1, newComboBox.Location.Y - 1);
                        borderLabel.BorderStyle = BorderStyle.FixedSingle;
                        borderLabel.BackColor = Color.White;
                        putPlace[cc.putPlaceNo].Controls.Add(borderLabel);

                        if(cc.Name.Length > 14 && cc.Name.Substring(0, 14) == "type_dassuiki_") {
                            newComboBox.TextChanged += new EventHandler(dassuikiTypeChange);
                        }
                    }
                    else if(cc.inputType == "NumericUpDown") {
                        NumericUpDownEx newNumericUpDown = new NumericUpDownEx();
                        newNumericUpDown.Name = cc.Name;
                        newNumericUpDown.Font = new Font("Meiryo UI", 9F, FontStyle.Regular, GraphicsUnit.Point, ((byte)(128)));
                        newNumericUpDown.Size = new Size(65, 21);
                        newNumericUpDown.Location = new Point(159, placeCount[cc.putPlaceNo] * pitchY + offsetY + 3);
                        newNumericUpDown.BorderStyle = BorderStyle.None;
                        newNumericUpDown.BackColor = Color.White;
                        newNumericUpDown.TextAlign = HorizontalAlignment.Right;

                        if(cc.Format == "N0") {
                            newNumericUpDown.DecimalPlaces = 0;
                            newNumericUpDown.Increment = 1M;
                        }
                        else if(cc.Format == "N1") {
                            newNumericUpDown.DecimalPlaces = 1;
                            newNumericUpDown.Increment = 0.1M;
                        }
                        else if(cc.Format == "N2") {
                            newNumericUpDown.DecimalPlaces = 2;
                            newNumericUpDown.Increment = 0.01M;
                        }
                        else if(cc.Format == "N3") {
                            newNumericUpDown.DecimalPlaces = 3;
                            newNumericUpDown.Increment = 0.001M;
                        }
                        else if(cc.Format == "N4") {
                            newNumericUpDown.DecimalPlaces = 4;
                            newNumericUpDown.Increment = 0.0001M;
                        }
                        else if(cc.Format == "N5") {
                            newNumericUpDown.DecimalPlaces = 5;
                            newNumericUpDown.Increment = 0.00001M;
                        }

                        newNumericUpDown.Maximum = (decimal)cc.Maximum;
                        newNumericUpDown.Minimum = (decimal)cc.Minimum;

                        ((TextBox)newNumericUpDown.Controls[1]).Text = null;

                        Label newValidationLabel = new Label();
                        newValidationLabel.Name = "vl_" + cc.Name;
                        newValidationLabel.Size = new Size(6, 21);
                        newValidationLabel.Location = new Point(223, placeCount[cc.putPlaceNo] * pitchY + offsetY + 1);
                        newValidationLabel.Padding = new Padding(0, 0, 0, 0);
                        newValidationLabel.BackColor = validationOK;
                        newValidationLabel.Text = "";
                        putPlace[cc.putPlaceNo].Controls.Add(newValidationLabel);

                        newNumericUpDown.Click += new EventHandler(numericUpDownAllFocus);
                        newNumericUpDown.GotFocus += new EventHandler(numericUpDownAllFocus);

                        if(cc.calculateSource) {
                            newNumericUpDown.ValueChanged += new EventHandler((sender, args) => calculate2ndValueStart(cc, sender, args));
                            newNumericUpDown.Leave += new EventHandler((sender, args) => calculate2ndValueStart(cc, sender, args));
                        }
                        else {
                            newNumericUpDown.ValueChanged += new EventHandler((sender, args) => noCalculate2ndValueStart(cc, sender, args));
                            newNumericUpDown.Leave += new EventHandler((sender, args) => noCalculate2ndValueStart(cc, sender, args));
                        }
                        
                        newNumericUpDown.ValueChanged += new EventHandler((sender, args) => numericUpDownChanged(cc.Format, sender, args));
                        newNumericUpDown.Leave += new EventHandler((sender, args) => numericUpDownChanged(cc.Format, sender, args));

                        if(!string.IsNullOrEmpty(cc.validMin.ToString()) && !string.IsNullOrEmpty(cc.validMax.ToString())) {
                            decimal min = (decimal)cc.validMin;
                            decimal max = (decimal)cc.validMax;
                            newNumericUpDown.ValueChanged += new EventHandler((sender, args) => numericUpDownValidation(min, max, newValidationLabel, sender, args));
                        }

                        putPlace[cc.putPlaceNo].Controls.Add(newNumericUpDown);

                        Label borderLabel = new Label();
                        borderLabel.Name = "bl_" + cc.Name;
                        borderLabel.Size = new Size(72, 23);
                        borderLabel.Location = new Point(newNumericUpDown.Location.X - 1, newNumericUpDown.Location.Y - 3);
                        borderLabel.BorderStyle = BorderStyle.FixedSingle;
                        borderLabel.BackColor = Color.White;
                        putPlace[cc.putPlaceNo].Controls.Add(borderLabel);
                    }

                    Label newLabel = new Label();
                    newLabel.Name = "tl_" + cc.Name;
                    newLabel.Text = cc.HeaderText + cc.unit;

                    if(cc.statical || cc.Name == "kanrisya" || cc.Name == "syorijou") {
                        newLabel.Font = new Font("Meiryo UI", 9F, FontStyle.Underline, GraphicsUnit.Point, ((byte)(128)));
                    }
                    else {
                        newLabel.Font = new Font("Meiryo UI", 9F, FontStyle.Regular, GraphicsUnit.Point, ((byte)(128)));
                    }

                    newLabel.AutoSize = true;
                    newLabel.Location = new Point(0, placeCount[cc.putPlaceNo] * pitchY + offsetY + 3);
                    newLabel.TextAlign = ContentAlignment.MiddleLeft;

                    putPlace[cc.putPlaceNo].Controls.Add(newLabel);

                    placeCount[cc.putPlaceNo]++;
                }
            }

            //タブ生成、パネル配置
            for(int i = 0; i < inputTabTitle.Count; i++) {
                TabPage newTabPage = new TabPage();
                newTabPage.Text = inputTabTitle[i];
                newTabPage.BorderStyle = BorderStyle.None;
                newTabPage.Font = new Font("Meiryo UI", 9F, FontStyle.Regular, GraphicsUnit.Point, ((byte)(128)));
                newTabPage.BackColor = Color.WhiteSmoke;
                newTabPage.AutoScroll = true;

                for(int j = 0; j < 4; j++) {
                    newTabPage.Controls.Add(putPlace[(i + 1) * 10 + j + 1]);
                }

                tabControl1.Controls.Add(newTabPage);

                if(newTabPage.Text.Length > 3) {
                    if(newTabPage.Text.Substring(0, 4) == "別途分析") {
                        Label newLabel1 = new Label();
                        newLabel1.Text = "注1 記載なき含有量の単位は[mg/L]";
                        newLabel1.Font = new Font("Meiryo UI", 9F, FontStyle.Regular, GraphicsUnit.Point, ((byte)(128)));
                        newLabel1.AutoSize = true;
                        newLabel1.Location = new Point(0, 465);
                        newLabel1.TextAlign = ContentAlignment.MiddleLeft;
                        newTabPage.Controls[3].Controls.Add(newLabel1);

                        Label newLabel2 = new Label();
                        newLabel2.Text = "注2 定量下限値以下は0、測定値なしは空欄";
                        newLabel2.Font = new Font("Meiryo UI", 9F, FontStyle.Regular, GraphicsUnit.Point, ((byte)(128)));
                        newLabel2.AutoSize = true;
                        newLabel2.Location = new Point(0, 482);
                        newLabel2.TextAlign = ContentAlignment.MiddleLeft;
                        newTabPage.Controls[3].Controls.Add(newLabel2);
                    }
                }
            }
        }




        //入力フォーム状態セット
        private void setInputForm() {
            if(!newRecord) {
                id = (int)dgv.Rows[curRow].Cells["id"].Value;
            }

            foreach(ColumnConfig cc in ccSet) {
                if(cc.Name != "id" && cc.Name != "del_flg" && cc.Name != "input_dt" && cc.Name != "seiten") {
                    //表示・非表示設定
                    bool itemVisible = (dgv.Columns[cc.Name].Visible || cc.Name == "kanrisya" || cc.Name == "syorijou");

                    putPlace[cc.putPlaceNo].Controls[cc.Name].Visible = itemVisible;
                    putPlace[cc.putPlaceNo].Controls["bl_" + cc.Name].Visible = itemVisible;

                    if(cc.inputType != "ComboBox" && !cc.calculatedDecimal && !cc.calculatedString) {
                        putPlace[cc.putPlaceNo].Controls["vl_" + cc.Name].Visible = itemVisible;
                    }

                    if(itemVisible) {
                        putPlace[cc.putPlaceNo].Controls["tl_" + cc.Name].ForeColor = Color.Black;
                    }
                    else {
                        putPlace[cc.putPlaceNo].Controls["tl_" + cc.Name].ForeColor = Color.LightGray;
                    }

                    //規定値・既入力値代入
                    if(cc.inputType == "TextBox") {
                        if(cc.statical || cc.Name == "kanrisya" || cc.Name == "syorijou") {
                            putPlace[cc.putPlaceNo].Controls[cc.Name].BackColor = lockedTB;
                            putPlace[cc.putPlaceNo].Controls["bl_" + cc.Name].BackColor = lockedTB;
                        }

                        if(!newRecord) {
                            ((TextBox)putPlace[cc.putPlaceNo].Controls[cc.Name]).Text = dgv.Rows[curRow].Cells[cc.Name].Value.ToString();
                            cc.previousValueStr = dgv.Rows[curRow].Cells[cc.Name].Value.ToString();
                        }
                        else {
                            cc.previousValueStr = null;

                            if(cc.Name == "kanrisya") {
                                ((TextBox)putPlace[cc.putPlaceNo].Controls[cc.Name]).Text = kanrisya;
                            }
                            else if(cc.Name == "syorijou") {
                                ((TextBox)putPlace[cc.putPlaceNo].Controls[cc.Name]).Text = syorijou;
                            }
                            else if(cc.statical) {
                                using(var con = new SQLiteConnection(DataBaseConfig.ConnectionString)) {
                                    con.Open();

                                    using(var cmd = con.CreateCommand()) {
                                        cmd.CommandText = "SELECT " + cc.Name + " FROM suishitsu_kanri WHERE del_flg IS NULL AND " + cc.Name + " 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)) {
                                                    ((TextBox)putPlace[cc.putPlaceNo].Controls[cc.Name]).Text = reader.GetString(0);
                                                }
                                                else {
                                                    ((TextBox)putPlace[cc.putPlaceNo].Controls[cc.Name]).Text = null;
                                                }
                                            }
                                            else {
                                                ((TextBox)putPlace[cc.putPlaceNo].Controls[cc.Name]).Text = null;
                                            }
                                        }
                                    }
                                }
                            }
                            else {
                                ((TextBox)putPlace[cc.putPlaceNo].Controls[cc.Name]).Text = null;
                            }
                        }
                    }
                    else if(cc.inputType == "DateTimePicker") {
                        if(!newRecord) {
                            ((DateTimePicker)putPlace[cc.putPlaceNo].Controls[cc.Name]).Value = DateTime.Parse(dgv.Rows[curRow].Cells[cc.Name].Value.ToString());

                            if(cc.Format == "yyyy/MM/dd ddd") {
                                cc.previousValueStr = ((DateTimePicker)putPlace[cc.putPlaceNo].Controls[cc.Name]).Value.ToString("yyyy-MM-dd") + " 00:00:00";
                            }
                            else if(cc.Format == "yyyy/MM/dd ddd HH:mm:ss") {
                                cc.previousValueStr = ((DateTimePicker)putPlace[cc.putPlaceNo].Controls[cc.Name]).Value.ToString("yyyy-MM-dd HH:mm:ss");
                            }
                        }
                        else {
                            ((DateTimePicker)putPlace[cc.putPlaceNo].Controls[cc.Name]).Value = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd") + " 00:00:00");

                            cc.previousValueStr = null;
                        }

                        if(cc.Name == "sokutei_dt") {
                            if(!newRecord) {
                                currentDate = DateTime.Parse(dgv.Rows[curRow].Cells[cc.Name].Value.ToString());
                                currentDate = DateTime.Parse(currentDate.ToString("yyyy-MM-dd") + " 00:00:00");
                            }
                            else {
                                currentDate = new DateTime(0);
                            }
                        }
                    }
                    else if(cc.inputType == "ComboBox") {
                        if(!newRecord) {
                            ((ComboBox)putPlace[cc.putPlaceNo].Controls[cc.Name]).SelectedItem = dgv.Rows[curRow].Cells[cc.Name].Value.ToString();
                            cc.previousValueStr = dgv.Rows[curRow].Cells[cc.Name].Value.ToString();
                        }
                        else {
                            cc.previousValueStr = null;

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

                                    using(var cmd = con.CreateCommand()) {
                                        cmd.CommandText = "SELECT " + cc.Name + " FROM suishitsu_kanri WHERE del_flg IS 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)) {
                                                    ((ComboBox)putPlace[cc.putPlaceNo].Controls[cc.Name]).SelectedItem = reader.GetString(0);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            else {
                                ((ComboBox)putPlace[cc.putPlaceNo].Controls[cc.Name]).SelectedIndex = 0;
                            }

                        }
                    }
                    else if(cc.inputType == "NumericUpDown") {
                        if(!newRecord) {
                            ((NumericUpDownEx)putPlace[cc.putPlaceNo].Controls[cc.Name]).Text = dgv.Rows[curRow].Cells[cc.Name].Value.ToString();

                            decimal preVal;

                            if(decimal.TryParse(dgv.Rows[curRow].Cells[cc.Name].Value.ToString(), out preVal)) {
                                cc.previousValueDec = preVal;
                            }
                            else {
                                cc.previousValueDec = null;
                            }
                        }
                        else {
                            cc.previousValueDec = null;

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

                                    using(var cmd = con.CreateCommand()) {
                                        cmd.CommandText = "SELECT " + cc.Name + " FROM suishitsu_kanri WHERE del_flg IS 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)) {
                                                    decimal? lastValue = FunctionForDatabase.decConvFromDB(reader.GetDecimal(0), cc.Format);

                                                    if(lastValue != null) {
                                                        ((NumericUpDownEx)putPlace[cc.putPlaceNo].Controls[cc.Name]).Value = (decimal)lastValue;
                                                    }
                                                    else {
                                                        ((TextBox)putPlace[cc.putPlaceNo].Controls[cc.Name].Controls[1]).Text = null;
                                                    }
                                                }
                                                else {
                                                    ((TextBox)putPlace[cc.putPlaceNo].Controls[cc.Name].Controls[1]).Text = null;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            else {
                                ((NumericUpDownEx)putPlace[cc.putPlaceNo].Controls[cc.Name]).Text = null;
                            }
                        }
                    }
                }
            }
        }




        //全入力枠の妥当性チェックを行う
        private void allInputBoxValidation() {
            foreach(ColumnConfig cc in ccSet) {
                if(cc.validNull) {
                    //TextBox空欄
                    if(string.IsNullOrEmpty(((TextBox)putPlace[cc.putPlaceNo].Controls[cc.Name]).Text)) {
                        putPlace[cc.putPlaceNo].Controls["vl_" + cc.Name].BackColor = validationNG;
                    }
                    else {
                        putPlace[cc.putPlaceNo].Controls["vl_" + cc.Name].BackColor = validationOK;
                    }
                }
                else if(cc.Name == "sokutei_dt") {
                    //測定日重複
                    string settedDateSTR = ((DateTimePicker)putPlace[cc.putPlaceNo].Controls[cc.Name]).Value.ToString("yyyy-MM-dd") + " 00:00:00";

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

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

                            cmd.CommandText = "SELECT COUNT(*) FROM suishitsu_kanri WHERE del_flg IS NULL AND kanrisya = '" + kanrisya + "' AND syorijou = '" + syorijou + "' AND sokutei_dt = '" + settedDateSTR + "';";

                            using(var reader = cmd.ExecuteReader()) {
                                if(reader.Read()) {
                                    if(!reader.IsDBNull(0)) {
                                        int count = reader.GetInt32(0);

                                        if(newRecord && count > 0 || !newRecord && count > 1) {
                                            putPlace[cc.putPlaceNo].Controls["vl_" + cc.Name].BackColor = validationNG;
                                            button1.Enabled = false;
                                        }
                                        else {
                                            putPlace[cc.putPlaceNo].Controls["vl_" + cc.Name].BackColor = validationOK;
                                            button1.Enabled = true;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                else if(!string.IsNullOrEmpty(cc.validMin.ToString()) && !string.IsNullOrEmpty(cc.validMax.ToString())) {
                    //NumericUpDown範囲外
                    if(!string.IsNullOrEmpty(((TextBox)putPlace[cc.putPlaceNo].Controls[cc.Name].Controls[1]).Text)) {
                        decimal min = (decimal)cc.validMin;
                        decimal max = (decimal)cc.validMax;

                        if(((NumericUpDownEx)putPlace[cc.putPlaceNo].Controls[cc.Name]).Value < min || ((NumericUpDownEx)putPlace[cc.putPlaceNo].Controls[cc.Name]).Value > max) {
                            putPlace[cc.putPlaceNo].Controls["vl_" + cc.Name].BackColor = validationNG;
                        }
                        else {
                            putPlace[cc.putPlaceNo].Controls["vl_" + cc.Name].BackColor = validationOK;
                        }
                    }
                    else {
                        putPlace[cc.putPlaceNo].Controls["vl_" + cc.Name].BackColor = validationOK;
                    }
                }
            }
        }




        //脱水機形式選択時のイベント
        private void dassuikiTypeChange(object sender, EventArgs e) {
            dassuikiTypeSet();
        }




        //ベルトプレス専用コントロールの表示を設定する
        private void dassuikiTypeSet() {
            for(int i = 1; i <= MaxSizeConfig.maxDassuiki; i++) {
                string ccName = "type_dassuiki_" + i.ToString();

                ComboBox settedComboBox = (ComboBox)putPlace[ColumnsConfigSet.nameToPutPlaceNo(ccName)].Controls[ccName];

                if(settedComboBox.SelectedItem.ToString() == "ベルトプレス") {
                    putPlace[ColumnsConfigSet.nameToPutPlaceNo("rofusp_dassuiki_" + i.ToString())].Controls["tl_rofusp_dassuiki_" + i.ToString()].ForeColor = Color.Black;
                    putPlace[ColumnsConfigSet.nameToPutPlaceNo("rofusp_dassuiki_" + i.ToString())].Controls["rofusp_dassuiki_" + i.ToString()].Visible = true;
                    putPlace[ColumnsConfigSet.nameToPutPlaceNo("rofusp_dassuiki_" + i.ToString())].Controls["vl_rofusp_dassuiki_" + i.ToString()].Visible = true;
                    putPlace[ColumnsConfigSet.nameToPutPlaceNo("rofusp_dassuiki_" + i.ToString())].Controls["bl_rofusp_dassuiki_" + i.ToString()].BackColor = Color.White;

                    putPlace[ColumnsConfigSet.nameToPutPlaceNo("rokasp_dassuiki_" + i.ToString())].Controls["tl_rokasp_dassuiki_" + i.ToString()].ForeColor = Color.Black;
                    putPlace[ColumnsConfigSet.nameToPutPlaceNo("rokasp_dassuiki_" + i.ToString())].Controls["rokasp_dassuiki_" + i.ToString()].Visible = true;
                    putPlace[ColumnsConfigSet.nameToPutPlaceNo("rokasp_dassuiki_" + i.ToString())].Controls["vl_rokasp_dassuiki_" + i.ToString()].Visible = true;
                    putPlace[ColumnsConfigSet.nameToPutPlaceNo("rokasp_dassuiki_" + i.ToString())].Controls["bl_rokasp_dassuiki_" + i.ToString()].BackColor = Color.White;
                }
                else {
                    putPlace[ColumnsConfigSet.nameToPutPlaceNo("rofusp_dassuiki_" + i.ToString())].Controls["tl_rofusp_dassuiki_" + i.ToString()].ForeColor = Color.Gray;
                    putPlace[ColumnsConfigSet.nameToPutPlaceNo("rofusp_dassuiki_" + i.ToString())].Controls["rofusp_dassuiki_" + i.ToString()].Visible = false;
                    putPlace[ColumnsConfigSet.nameToPutPlaceNo("rofusp_dassuiki_" + i.ToString())].Controls["vl_rofusp_dassuiki_" + i.ToString()].Visible = false;
                    putPlace[ColumnsConfigSet.nameToPutPlaceNo("rofusp_dassuiki_" + i.ToString())].Controls["bl_rofusp_dassuiki_" + i.ToString()].BackColor = Color.LightGray;

                    putPlace[ColumnsConfigSet.nameToPutPlaceNo("rokasp_dassuiki_" + i.ToString())].Controls["tl_rokasp_dassuiki_" + i.ToString()].ForeColor = Color.Gray;
                    putPlace[ColumnsConfigSet.nameToPutPlaceNo("rokasp_dassuiki_" + i.ToString())].Controls["rokasp_dassuiki_" + i.ToString()].Visible = false;
                    putPlace[ColumnsConfigSet.nameToPutPlaceNo("rokasp_dassuiki_" + i.ToString())].Controls["vl_rokasp_dassuiki_" + i.ToString()].Visible = false;
                    putPlace[ColumnsConfigSet.nameToPutPlaceNo("rokasp_dassuiki_" + i.ToString())].Controls["bl_rokasp_dassuiki_" + i.ToString()].BackColor = Color.LightGray;
                }
            }
        }




        //NumericUpDownフォーカス時に数字を選択状態にする
        private void numericUpDownAllFocus(object sender, EventArgs e) {
            NumericUpDownEx n = (NumericUpDownEx)sender;
            int NumberLength = ((TextBox)n.Controls[1]).TextLength;
            ((TextBox)n.Controls[1]).Select(0, NumberLength);
        }




        //NumericUpDown値変更時に妥当な範囲にあるかチェックを行う
        private void numericUpDownValidation(decimal min, decimal max, Label validationLabel, object sender, EventArgs e) {
            NumericUpDownEx n = (NumericUpDownEx)sender;

            if(n.Value < min || n.Value > max) {
                validationLabel.BackColor = validationNG;
            }
            else {
                validationLabel.BackColor = validationOK;
            }
        }




        //NumericUpDown値変更時のイベント
        private void numericUpDownChanged(string format, object sender, EventArgs e) {
            //データごとの規定の小数点以下桁数に切捨て
            NumericUpDownEx n = (NumericUpDownEx)sender;

            if(format == "N0") {
                n.Value = Math.Truncate(n.Value);
            }
            else if(format == "N1") {
                n.Value = Math.Truncate(n.Value * 10) / 10;
            }
            else if(format == "N2") {
                n.Value = Math.Truncate(n.Value * 100) / 100;
            }
            else if(format == "N3") {
                n.Value = Math.Truncate(n.Value * 1000) / 1000;
            }
            else if(format == "N4") {
                n.Value = Math.Truncate(n.Value * 10000) / 10000;
            }
            else if(format == "N5") {
                n.Value = Math.Truncate(n.Value * 100000) / 100000;
            }
        }




        //二次データ計算開始イベント
        private void calculate2ndValueStart(ColumnConfig cc, object sender, EventArgs e) {
            if(!initializing) {
                calculate2ndValue(false, cc);
            }
        }




        //二次データの計算およびコントロールの値変更時の表示変更
        private void calculate2ndValue(bool first = false, ColumnConfig changedcc = null) {
            tempValueSetColumnConfig();

            foreach(ColumnConfig cc in ccSet) {
                if(changedcc != null) {
                    valueChangedSetting(changedcc);

                    if(changedcc.forCalc != null && Array.IndexOf(changedcc.forCalc, cc.Name) < 0) {
                        continue;
                    }
                }

                if(cc.calculatedDecimal) {
                    decimal? retValue = Calculate2ndValue.calc2ndDecimal(cc.Name, dgv1Row: null, ccSet: ccSet);

                    if(retValue != null) {
                        decimal retNumber = (decimal)retValue;
                        putPlace[cc.putPlaceNo].Controls[cc.Name].Text = retNumber.ToString();

                        if(first) {
                            cc.previousValueStr = retNumber.ToString();
                        }
                    }
                    else {
                        putPlace[cc.putPlaceNo].Controls[cc.Name].Text = null;

                        if(first) {
                            cc.previousValueStr = null;
                        }
                    }

                    if(!first) {
                        valueChangedSetting(cc);
                    }
                }
            }
        }




        //二次データに関係しないコントロールの値変更時の表示変更
        private void noCalculate2ndValueStart(ColumnConfig cc, object sender, EventArgs e) {
            if(!initializing) {
                valueChangedSetting(cc);
            }
        }




        //コントロールの値が変更された場合は表示を変更する
        private void valueChangedSetting(ColumnConfig cc) {
            if(cc.Name != "id" && cc.Name != "del_flg" && cc.Name != "input_dt" && cc.Name != "seiten") {
                if(cc.calculatedDecimal || cc.calculatedString) {
                    Label settedLabel = (Label)putPlace[cc.putPlaceNo].Controls[cc.Name];

                    if(settedLabel.Text != cc.previousValueStr) {
                        settedLabel.ForeColor = hasChanged2V;
                        formChanged = true;
                    }
                    else {
                        settedLabel.ForeColor = noChanged2V;
                    }
                }
                else if(cc.inputType == "TextBox") {
                    TextBox settedTextBox = (TextBox)putPlace[cc.putPlaceNo].Controls[cc.Name];

                    if(settedTextBox.Text != cc.previousValueStr) {
                        settedTextBox.ForeColor = hasChanged;
                        formChanged = true;
                    }
                    else {
                        settedTextBox.ForeColor = noChanged;
                    }
                }
                else if(cc.inputType == "DateTimePicker") {
                    DateTimePicker settedDateTimePicker = (DateTimePicker)putPlace[cc.putPlaceNo].Controls[cc.Name];
                    string settedDateTimePickerStr = null;

                    if(cc.Format == "yyyy/MM/dd ddd") {
                        settedDateTimePickerStr = settedDateTimePicker.Value.ToString("yyyy-MM-dd") + " 00:00:00";
                    }
                    else if(cc.Format == "yyyy/MM/dd ddd HH:mm:ss") {
                        settedDateTimePickerStr = settedDateTimePicker.Value.ToString("yyyy-MM-dd HH:mm:ss");
                    }

                    if(settedDateTimePickerStr != cc.previousValueStr) {
                        settedDateTimePicker.Font = new Font(settedDateTimePicker.Font, FontStyle.Italic);
                        formChanged = true;
                    }
                    else {
                        settedDateTimePicker.Font = new Font(settedDateTimePicker.Font, FontStyle.Regular);
                    }
                }
                else if(cc.inputType == "ComboBox") {
                    ComboBox settedComboBox = (ComboBox)putPlace[cc.putPlaceNo].Controls[cc.Name];

                    if(settedComboBox.SelectedItem.ToString() != cc.previousValueStr) {
                        settedComboBox.ForeColor = hasChanged;
                        formChanged = true;
                    }
                    else {
                        settedComboBox.ForeColor = noChanged;
                    }
                }
                else if(cc.inputType == "NumericUpDown") {
                    NumericUpDownEx settedNumericUpDown = (NumericUpDownEx)putPlace[cc.putPlaceNo].Controls[cc.Name];
                    decimal? settedNumericUpDownDec = null;

                    if(!String.IsNullOrEmpty(((TextBox)settedNumericUpDown.Controls[1]).Text)) {
                        settedNumericUpDownDec = settedNumericUpDown.Value;
                    }

                    if(settedNumericUpDownDec != cc.previousValueDec) {
                        settedNumericUpDown.ForeColor = hasChanged;
                        formChanged = true;
                    }
                    else {
                        settedNumericUpDown.ForeColor = noChanged;
                    }
                }
            }
        }




        //コントロールの表示の初期化
        private void presetValueChangedSetting() {
            foreach(ColumnConfig cc in ccSet) {
                if(cc.Name != "id" && cc.Name != "del_flg" && cc.Name != "input_dt" && cc.Name != "seiten") {
                    if(cc.calculatedDecimal || cc.calculatedString) {
                        Label settedLabel = (Label)putPlace[cc.putPlaceNo].Controls[cc.Name];
                        settedLabel.ForeColor = noChanged2V;
                    }
                    else if(cc.inputType == "TextBox") {
                        TextBox settedTextBox = (TextBox)putPlace[cc.putPlaceNo].Controls[cc.Name];
                        settedTextBox.ForeColor = noChanged;
                    }
                    else if(cc.inputType == "DateTimePicker") {
                        DateTimePicker settedDateTimePicker = (DateTimePicker)putPlace[cc.putPlaceNo].Controls[cc.Name];
                        settedDateTimePicker.Font = new Font(settedDateTimePicker.Font, FontStyle.Regular);
                    }
                    else if(cc.inputType == "ComboBox") {
                        ComboBox settedComboBox = (ComboBox)putPlace[cc.putPlaceNo].Controls[cc.Name];
                        settedComboBox.ForeColor = noChanged;
                    }
                    else if(cc.inputType == "NumericUpDown") {
                        NumericUpDownEx settedNumericUpDown = (NumericUpDownEx)putPlace[cc.putPlaceNo].Controls[cc.Name];
                        settedNumericUpDown.ForeColor = noChanged;
                    }
                }
            }
        }




        //staticalなTextBoxのクリック時に背景色を変更する
        private void staticalTextBoxVisit(object sender, EventArgs e) {
            TextBox n = (TextBox)sender;
            n.BackColor = unlockedTB;

            Label borderLabel = (Label)putPlace[ColumnsConfigSet.nameToPutPlaceNo(n.Name)].Controls["bl_" + n.Name];
            borderLabel.BackColor = unlockedTB;
        }




        //staticalなTextBoxからフォーカスが外れた時に背景色を変更する
        private void staticalTextBoxExit(object sender, EventArgs e) {
            TextBox n = (TextBox)sender;
            n.BackColor = lockedTB;

            Label borderLabel = (Label)putPlace[ColumnsConfigSet.nameToPutPlaceNo(n.Name)].Controls["bl_" + n.Name];
            borderLabel.BackColor = lockedTB;
        }




        //空欄不可のTextBox値変更時に空欄のチェックを行う
        private void textBoxValidation(Label validationLabel, object sender, EventArgs e) {
            TextBox n = (TextBox)sender;

            if(string.IsNullOrEmpty(n.Text)) {
                validationLabel.BackColor = validationNG;
            }
            else {
                validationLabel.BackColor = validationOK;
            }
        }




        //管理者・処理場・測定日の変更時に重複がないかチェックを行う
        private void sokutei_dtValidation(object sender, EventArgs e) {
            string sokutei_dtTempSTR = ((DateTimePicker)putPlace[ColumnsConfigSet.nameToPutPlaceNo("sokutei_dt")].Controls["sokutei_dt"]).Value.ToString("yyyy-MM-dd") + " 00:00:00";
            DateTime sokutei_dtTemp = DateTime.Parse(sokutei_dtTempSTR);

            string kanrisyaTemp = ((TextBox)putPlace[ColumnsConfigSet.nameToPutPlaceNo("kanrisya")].Controls["kanrisya"]).Text;
            string syorijouTemp = ((TextBox)putPlace[ColumnsConfigSet.nameToPutPlaceNo("syorijou")].Controls["syorijou"]).Text;

            Label vl_sokutei_dt = (Label)putPlace[ColumnsConfigSet.nameToPutPlaceNo("sokutei_dt")].Controls["vl_sokutei_dt"];

            if(!newRecord && sokutei_dtTemp == currentDate && kanrisyaTemp == kanrisya && syorijouTemp == syorijou) {
                vl_sokutei_dt.BackColor = validationOK;
                button1.Enabled = true;
            }
            else {
                using(var con = new SQLiteConnection(DataBaseConfig.ConnectionString)) {
                    con.Open();

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

                        cmd.CommandText = "SELECT * FROM suishitsu_kanri WHERE del_flg IS NULL AND kanrisya = '" + kanrisyaTemp + "' AND syorijou = '" + syorijouTemp + "' AND sokutei_dt = '" + sokutei_dtTempSTR + "';";

                        using(var reader = cmd.ExecuteReader()) {
                            if(reader.HasRows) {
                                vl_sokutei_dt.BackColor = validationNG;
                                button1.Enabled = false;
                            }
                            else {
                                vl_sokutei_dt.BackColor = validationOK;
                                button1.Enabled = true;
                            }
                        }
                    }
                }
            }
        }




        //フォームの値をColumnConfigに一時格納する
        private void tempValueSetColumnConfig() {
            foreach(ColumnConfig cc in ccSet) {
                if(cc.Name != "id" && cc.Name != "del_flg" && cc.Name != "input_dt" && cc.Name != "seiten" && !cc.calculatedDecimal && !cc.calculatedString) {
                    if(cc.inputType == "TextBox") {
                        TextBox settedTextBox = (TextBox)putPlace[cc.putPlaceNo].Controls[cc.Name];
                        cc.tempValueStr = settedTextBox.Text;
                    }
                    else if(cc.inputType == "DateTimePicker") {
                        DateTimePicker settedDateTimePicker = (DateTimePicker)putPlace[cc.putPlaceNo].Controls[cc.Name];

                        if(cc.Format == "yyyy/MM/dd ddd") {
                            cc.tempValueStr = settedDateTimePicker.Value.ToString("yyyy-MM-dd") + " 00:00:00";
                        }
                        else if(cc.Format == "yyyy/MM/dd ddd HH:mm:ss") {
                            cc.tempValueStr = settedDateTimePicker.Value.ToString("yyyy-MM-dd HH:mm:ss");
                        }

                        if(cc.Name == "sokutei_dt") {
                            sokutei_dt = settedDateTimePicker.Value;
                        }
                    }
                    else if(cc.inputType == "ComboBox") {
                        ComboBox settedComboBox = (ComboBox)putPlace[cc.putPlaceNo].Controls[cc.Name];
                        cc.tempValueStr = settedComboBox.SelectedItem.ToString();
                    }
                    else if(cc.inputType == "NumericUpDown") {
                        NumericUpDownEx settedNumericUpDown = (NumericUpDownEx)putPlace[cc.putPlaceNo].Controls[cc.Name];

                        if(!String.IsNullOrEmpty(((TextBox)settedNumericUpDown.Controls[1]).Text)) {
                            cc.tempValueDec = settedNumericUpDown.Value;
                        }
                        else {
                            cc.tempValueDec = null;
                        }
                    }
                }
            }
        }




        //追加・変更ボタンクリックイベント
        private void button1_Click(object sender, EventArgs e) {
            calculate2ndValue();

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

                int duplicationColumnNo = 0;

                string input_dtSTR = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                string kanrisyaTemp = ccSet[ColumnsConfigSet.nameToIndex("kanrisya")].tempValueStr;
                string syorijouTemp = ccSet[ColumnsConfigSet.nameToIndex("syorijou")].tempValueStr;
                string sokutei_dtTempSTR = ccSet[ColumnsConfigSet.nameToIndex("sokutei_dt")].tempValueStr;
                DateTime sokutei_dtTemp = DateTime.Parse(sokutei_dtTempSTR);

                kanrisya = kanrisyaTemp;
                syorijou = syorijouTemp;

                //同一管理者・処理場・測定日の重複レコードがないか確認
                using(var cmd = con.CreateCommand()) {
                    cmd.CommandText = "SELECT COUNT(*) FROM suishitsu_kanri WHERE del_flg IS NULL AND kanrisya = @kanrisya AND syorijou = @syorijou AND sokutei_dt = @sokutei_dt;";

                    cmd.Parameters.Add(new SQLiteParameter("@kanrisya", kanrisyaTemp));
                    cmd.Parameters.Add(new SQLiteParameter("@syorijou", syorijouTemp));
                    cmd.Parameters.Add(new SQLiteParameter("@sokutei_dt", sokutei_dtTempSTR));

                    using(var reader = cmd.ExecuteReader()) {
                        if(reader.Read()) {
                            if(!reader.IsDBNull(0)) {
                                duplicationColumnNo = reader.GetInt32(0);
                            }
                        }
                    }
                }

                if(duplicationColumnNo == 0) {
                    //重複なし
                    if(newRecord) {
                        //新規追加
                        //管理者・処理場・測定日のみで挿入しレコードのidを取得
                        using(var transaction = con.BeginTransaction()) {
                            try {
                                using(var cmd = con.CreateCommand()) {
                                    cmd.CommandText = "INSERT INTO suishitsu_kanri(kanrisya, syorijou, sokutei_dt, input_dt) VALUES(@kanrisya, @syorijou, @sokutei_dt, @input_dt);";

                                    cmd.Parameters.Add(new SQLiteParameter("@kanrisya", kanrisyaTemp));
                                    cmd.Parameters.Add(new SQLiteParameter("@syorijou", syorijouTemp));
                                    cmd.Parameters.Add(new SQLiteParameter("@sokutei_dt", sokutei_dtTempSTR));
                                    cmd.Parameters.Add(new SQLiteParameter("@input_dt", input_dtSTR));

                                    cmd.ExecuteNonQuery();
                                }

                                transaction.Commit();
                                dbChanged = true;
                            }
                            catch(Exception ex) {
                                transaction.Rollback();
                                MessageBox.Show(ex.Message);
                                return;
                            }
                        }

                        using(var cmd = con.CreateCommand()) {
                            cmd.CommandText = "SELECT id FROM suishitsu_kanri WHERE ROWID = last_insert_rowid();";

                            using(var reader = cmd.ExecuteReader()) {
                                if(reader.Read()) {
                                    if(!reader.IsDBNull(0)) {
                                        id = reader.GetInt32(0);
                                    }
                                }
                            }
                        }
                    }
                    else {
                        //変更(管理者・処理場・測定日のいずれかが変更となる場合)
                        //現在のレコードのidをそのまま利用
                    }
                }
                else {
                    if(!newRecord && sokutei_dtTemp == currentDate && kanrisyaTemp == kanrisya && syorijouTemp == syorijou && duplicationColumnNo == 1) {
                        //変更(重複レコードが1件あるが管理者・処理場・測定日が同じ＝管理者・処理場・測定日を変更しない通常の変更)
                        //管理者・処理場・測定日でレコードのidを取得
                        using(var cmd = con.CreateCommand()) {
                            cmd.CommandText = "SELECT id FROM suishitsu_kanri WHERE del_flg IS NULL AND kanrisya = @kanrisya AND syorijou = @syorijou AND sokutei_dt = @sokutei_dt;";

                            cmd.Parameters.Add(new SQLiteParameter("@kanrisya", kanrisyaTemp));
                            cmd.Parameters.Add(new SQLiteParameter("@syorijou", syorijouTemp));
                            cmd.Parameters.Add(new SQLiteParameter("@sokutei_dt", sokutei_dtTempSTR));

                            using(var reader = cmd.ExecuteReader()) {
                                if(reader.Read()) {
                                    if(!reader.IsDBNull(0)) {
                                        id = reader.GetInt32(0);
                                    }
                                }
                            }
                        }
                    }
                    else {
                        //それ以外で重複レコードがある＝エラー
                        MessageBox.Show("既に変更後の管理者、処理場、測定日と同じデータがあるため、変更できません");
                        return;
                    }
                }

                //取得したidのレコードにデータを記入
                if(id > 0) {
                    int syncColumnNo = 900;

                    for(int i = 0; i <= (int)Math.Floor((decimal)ccSet.Count / syncColumnNo); i++) {
                        using(var transaction = con.BeginTransaction()) {
                            try {
                                int changedColumn = 0;

                                using(var cmd = con.CreateCommand()) {
                                    string sql1 = "UPDATE suishitsu_kanri SET ";
                                    string sql2 = "";
                                    string sql3 = " WHERE id = @id;";

                                    for(int j = 1; j <= syncColumnNo; j++) {
                                        if(i * syncColumnNo + j >= ccSet.Count) {
                                            break;
                                        }

                                        ColumnConfig cc = ccSet[i * syncColumnNo + j];
                                        bool hasChanged = false;

                                        //変更のあった要素のみUPDATE
                                        if(cc.Name != "id" && cc.Name != "del_flg" && cc.Name != "seiten") {
                                            if(cc.calculatedDecimal || cc.calculatedString) {
                                                Label settedLabel = (Label)putPlace[cc.putPlaceNo].Controls[cc.Name];

                                                if(settedLabel.Text != cc.previousValueStr) {
                                                    hasChanged = true;
                                                }
                                            }
                                            else if(cc.inputType == "TextBox") {
                                                TextBox settedTextBox = (TextBox)putPlace[cc.putPlaceNo].Controls[cc.Name];

                                                if(settedTextBox.Text != cc.previousValueStr) {
                                                    hasChanged = true;
                                                }
                                            }
                                            else if(cc.inputType == "DateTimePicker") {
                                                DateTimePicker settedDateTimePicker = (DateTimePicker)putPlace[cc.putPlaceNo].Controls[cc.Name];
                                                string settedDateTimePickerStr = null;

                                                if(cc.Format == "yyyy/MM/dd ddd") {
                                                    settedDateTimePickerStr = settedDateTimePicker.Value.ToString("yyyy-MM-dd") + " 00:00:00";
                                                }
                                                else if(cc.Format == "yyyy/MM/dd ddd HH:mm:ss") {
                                                    settedDateTimePickerStr = settedDateTimePicker.Value.ToString("yyyy-MM-dd HH:mm:ss");
                                                }

                                                if(settedDateTimePickerStr != cc.previousValueStr) {
                                                    hasChanged = true;
                                                }
                                            }
                                            else if(cc.inputType == "ComboBox") {
                                                ComboBox settedComboBox = (ComboBox)putPlace[cc.putPlaceNo].Controls[cc.Name];

                                                if(settedComboBox.SelectedItem.ToString() != cc.previousValueStr) {
                                                    hasChanged = true;
                                                }
                                            }
                                            else if(cc.inputType == "NumericUpDown") {
                                                NumericUpDownEx settedNumericUpDown = (NumericUpDownEx)putPlace[cc.putPlaceNo].Controls[cc.Name];
                                                decimal? settedNumericUpDownDec = null;

                                                if(!String.IsNullOrEmpty(((TextBox)settedNumericUpDown.Controls[1]).Text)) {
                                                    settedNumericUpDownDec = settedNumericUpDown.Value;
                                                }

                                                if(settedNumericUpDownDec != cc.previousValueDec) {
                                                    hasChanged = true;
                                                }
                                            }

                                            if(hasChanged) {
                                                if(changedColumn > 0) {
                                                    sql2 += ", ";
                                                }

                                                sql2 += cc.Name + " = @p" + changedColumn.ToString();

                                                cmd.Parameters.Add(makeSQLiteParameter(cc, changedColumn, input_dtSTR));

                                                changedColumn++;
                                            }
                                        }
                                    }

                                    if(changedColumn > 0) {
                                        cmd.CommandText = sql1 + sql2 + sql3;
                                        cmd.Parameters.Add(new SQLiteParameter("@id", id));

                                        cmd.ExecuteNonQuery();
                                    }
                                }

                                if(changedColumn > 0) {
                                    transaction.Commit();
                                    dbChanged = true;
                                }
                            }
                            catch(Exception ex) {
                                transaction.Rollback();
                                MessageBox.Show(ex.Message);
                            }
                        }
                    }
                }
            }

            this.Close();
        }




        //行ごとのSQLiteパラメータ生成
        private SQLiteParameter makeSQLiteParameter(ColumnConfig cc, int i, string input_dtSTR) {
            SQLiteParameter newSQLiteParameter;

            if(cc.Name == "seiten") {
                newSQLiteParameter = new SQLiteParameter("@p" + i.ToString(), null);
            }
            else if(cc.calculatedDecimal) {
                //二次データ(数値)
                decimal? newValue = Calculate2ndValue.calc2ndDecimal(cc.Name, dgv1Row: null, ccSet: ccSet);

                newValue = FunctionForDatabase.decConvForDB(newValue, cc.Format);

                newSQLiteParameter = new SQLiteParameter("@p" + i.ToString(), newValue);
            }
            else if(cc.calculatedString) {
                //二次データ(文字)
                newSQLiteParameter = new SQLiteParameter("@p" + i.ToString(), Calculate2ndValue.calc2ndString(cc.Name, dgv1Row: null, ccSet: ccSet));
            }
            else if(cc.Name == "input_dt") {
                //入力日
                newSQLiteParameter = new SQLiteParameter("@p" + i.ToString(), input_dtSTR);
            }
            else if(cc.inputType == "TextBox" || cc.inputType == "DateTimePicker" || cc.inputType == "ComboBox") {
                //一次データ(文字)
                string tString = null;

                if(!string.IsNullOrEmpty(cc.tempValueStr)){
                    tString = cc.tempValueStr;
                }

                newSQLiteParameter = new SQLiteParameter("@p" + i.ToString(), tString);
            }
            else if(cc.inputType == "NumericUpDown") {
                //一次データ(数値)
                decimal? newValue = FunctionForDatabase.decConvForDB(cc.tempValueDec, cc.Format);

                newSQLiteParameter = new SQLiteParameter("@p" + i.ToString(), newValue);
            }
            else {
                newSQLiteParameter = new SQLiteParameter("@p" + i.ToString(), null);
            }

            return newSQLiteParameter;
        }




        //キャンセルボタンクリックイベント
        private void button2_Click(object sender, EventArgs e) {
            //変更されたコントロールがある場合は確認表示

            if(formChanged) {
                if(MessageBox.Show("入力画面を閉じてよいですか\n編集内容は破棄されます", "", MessageBoxButtons.OKCancel, MessageBoxIcon.None, MessageBoxDefaultButton.Button2) == DialogResult.Cancel) {
                    return;
                }
            }

            this.Close();
        }

    }
}
