【解決方法】Datagridview が常に埋まっているわけではありません


現在、製品のカテゴリとサブカテゴリごとにいくつかの検査を行う必要があるプロジェクトに取り組んでいます。 私の winform の仕組みは次のとおりです。

1.カテゴリを示す最初のコンボボックスをクリックします。

https://i.stack.imgur.com/lzFIX.png[^]

2. 2 番目のコンボボックスでサブカテゴリを選択します

https://i.stack.imgur.com/zsOta.png[^]

3.データグリッドビューが生成され、それ自体でいくつかのデータ測定サンプルが生成されます。 検査基準に応じて、1、3、5、または 7 の評価が得られます。 メジャーの最大数 n を取得し、列を n 回生成しますが、khttps://i.stack.imgur.com/xF0i1.png[^]

私が直面している問題は、初回のみ満たされ、他の回は満たされないということです。 誰か手伝ってくれませんか?

私が試したこと:

私が使用しているコードは次のとおりです。

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
            {
             foreach (DataGridViewRow row in dataGridView2.Rows)
            {
                row.Cells["toleranceMinDataGridViewTextBoxColumn"].Value = "";
                row.Cells["toleranceNomDataGridViewTextBoxColumn"].Value = "";
                row.Cells["toleranceMaxDataGridViewTextBoxColumn"].Value = "";

                row.Cells["toleranceMinDataGridViewTextBoxColumn"].ReadOnly = false;
                row.Cells["toleranceNomDataGridViewTextBoxColumn"].ReadOnly = false;
                row.Cells["toleranceMaxDataGridViewTextBoxColumn"].ReadOnly = false;

            }
                if (!string.IsNullOrEmpty(comboBox1.Text))
                {
                    string connectionstr2 = "Data Source = (LocalDB)\\MSSQLLocalDB; Integrated Security = True";
                    SqlConnection cn2 = new SqlConnection(connectionstr2);
                    SqlDataAdapter da2 = new SqlDataAdapter();
                    SqlCommand cmd2 = new System.Data.SqlClient.SqlCommand();
                    System.Data.DataTable dt2 = new System.Data.DataTable();
                    string a = comboBox1.Text;
                    cmd2.CommandText = $"SELECT section FROM Type where typee = '{a}' ";
                    da2.SelectCommand = cmd2;
                    da2.SelectCommand.Connection = cn2;
                    da2.Fill(dt2);
                    comboBox2.Enabled = true;
                    comboBox2.DisplayMember = "section";
                    comboBox2.ValueMember = "section";
                    comboBox2.DataSource = dt2;
                    comboBox2.SelectedIndex = -1;


            }
        }
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
            {
            string w = comboBox2.Text;
            int t = 0;
            foreach (DataGridViewRow row in dataGridView2.Rows)
            {
                row.Cells["toleranceMinDataGridViewTextBoxColumn"].Value = "";
                row.Cells["toleranceNomDataGridViewTextBoxColumn"].Value = "";
                row.Cells["toleranceMaxDataGridViewTextBoxColumn"].Value = "";

                row.Cells["toleranceMinDataGridViewTextBoxColumn"].ReadOnly = false;
                row.Cells["toleranceNomDataGridViewTextBoxColumn"].ReadOnly = false;
                row.Cells["toleranceMaxDataGridViewTextBoxColumn"].ReadOnly = false;

            }
            if (!string.IsNullOrEmpty(comboBox2.Text))
                {
                
                nombredemesures = new int[] { };

                    dataGridView2.DataSource = null;
                    dataGridView2.Rows.Clear();
                    dataGridView2.DataSource = this.dataSet1.Tolerance;
                    dataGridView2.Columns.OfType<DataGridViewColumn>().ToList().ForEach(col => col.Visible = false);
                    richTextBox1.Text = comboBox1.Text + comboBox2.Text;
                    dataGridView2.Columns["lotDataGridViewTextBoxColumn"].Visible = true;
                    dataGridView2.Columns["ItemDataGridViewTextBoxColumn"].Visible = true;
                    dataGridView2.Columns["lotDataGridViewTextBoxColumn"].Visible = true;
                    dataGridView2.Columns["ItemDataGridViewTextBoxColumn"].Visible = true;
                    dataGridView2.Columns["toleranceMinDataGridViewTextBoxColumn"].Visible = true;
                    dataGridView2.Columns["toleranceNomDataGridViewTextBoxColumn"].Visible = true;
                    dataGridView2.Columns["toleranceMaxDataGridViewTextBoxColumn"].Visible = true;


                    dataGridView2.Columns[$"toleranceMinDataGridViewTextBoxColumn"].DefaultCellStyle.BackColor = System.Drawing.Color.Wheat;
                    dataGridView2.Columns[$"toleranceNomDataGridViewTextBoxColumn"].DefaultCellStyle.BackColor = System.Drawing.Color.Wheat;
                    dataGridView2.Columns[$"toleranceMaxDataGridViewTextBoxColumn"].DefaultCellStyle.BackColor = System.Drawing.Color.Wheat;
                int deb1 = 0;
                int fin1 = 0;
                int deb2 = 0;
                int fin2 = 0;
                int deb3 = 0;
                int fin3 = 0;
                var result = from DataGridViewRow row in dataGridView2.Rows where row.Cells[$"{comboBox1.Text + comboBox2.Text}DataGridViewTextBoxColumn"].Value.ToString() is "" select row;

                List<DataGridViewRow> lignes = result.ToList();
                foreach (DataGridViewRow row in dataGridView2.Rows)
                {
                    if (row.Cells["lotDataGridViewTextBoxColumn"].Value?.ToString() is "1")
                    {
                        if (deb1 == 0)
                        {
                            deb1 = row.Index;
                        }
                    }
                    else if (row.Cells["lotDataGridViewTextBoxColumn"].Value?.ToString() is "2")
                    {
                        if (deb2 == 0)
                        {
                            deb2 = row.Index;
                            fin1 = row.Index - 1;
                        }
                    }
                    else if (row.Cells["lotDataGridViewTextBoxColumn"].Value?.ToString() is "3")
                    {
                        if (deb3 == 0)
                        {
                            fin2 = row.Index - 1;
                            deb3 = row.Index;
                        }
                    }

                }

                fin3 = lignes.Count;
                //lot1
                var cell1 = (DataGridViewTextBoxCellEx)dataGridView2.Rows[deb1].Cells["lotDataGridViewTextBoxColumn"];
                cell1.RowSpan = fin1 - deb1 + 1;
                cell1.Value = "1";
                cell1.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;


                var cell2 = (DataGridViewTextBoxCellEx)dataGridView2.Rows[deb2].Cells["lotDataGridViewTextBoxColumn"];
                cell2.RowSpan = fin2 - deb2 + 1;
                cell2.Value = "2";
                cell2.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;

                var cell3 = (DataGridViewTextBoxCellEx)dataGridView2.Rows[deb3].Cells["lotDataGridViewTextBoxColumn"];
                cell3.RowSpan = fin3 - deb3 + 1;
                cell3.Value = "3";
                cell3.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;

                foreach (DataGridViewRow row in dataGridView2.Rows)
                    {


                        CurrencyManager currencyManager1 = (CurrencyManager)BindingContext[dataGridView2.DataSource];
                        int i = row.Index;
                        currencyManager1.SuspendBinding();

                        if ((row.Cells[$"{comboBox1.Text + comboBox2.Text}DataGridViewTextBoxColumn"].Value?.ToString() is "")&&(row.Cells["toleranceMaxDataGridViewTextBoxColumn"].Value?.ToString() is ""))
                        {


                            row.Visible = false;
                        }
                        else
                        {
                            t++;
                            string[] splitter = new string[3];
                            try
                            {
                                string a = dataGridView2.Rows[row.Index].Cells[$"{comboBox1.Text + comboBox2.Text}DataGridViewTextBoxColumn"].Value == null ? string.Empty : dataGridView2.Rows[row.Index].Cells[$"{comboBox1.Text + comboBox2.Text}DataGridViewTextBoxColumn"].Value.ToString();

                                if (a.Contains('-'))
                                {
                                    splitter = a.Split('-');
                                    row.Cells["toleranceMinDataGridViewTextBoxColumn"].Value = splitter[0];
                                    row.Cells["toleranceNomDataGridViewTextBoxColumn"].Value = splitter[1];
                                    row.Cells["toleranceMaxDataGridViewTextBoxColumn"].Value = splitter[2];


                                }
                                else
                                {
                                    row.Cells["toleranceNomDataGridViewTextBoxColumn"].Value = a;

                                }



                            }
                            catch (Exception ex)
                            {
                                Debug.WriteLine(ex.ToString());
                            }


                        }








                        currencyManager1.ResumeBinding();


                    }


                }
           if (!(string.IsNullOrEmpty(comboBox2.Text)))
            {
                List<int> intValues = new List<int>();
                foreach (DataGridViewRow row in dataGridView2.Rows)
                {

                    if (!(row.Cells[$"{comboBox1.Text + comboBox2.Text}DataGridViewTextBoxColumn"].Value?.ToString() is ""))
                    {
                        var a = row.Cells[$"donnees{comboBox1.Text + comboBox2.Text}DataGridViewTextBoxColumn"].Value;
                        if (!(a is DBNull))
                        {
                            intValues.Add(Convert.ToInt32(a));
                        }


                    }
                }
                int max = 0;
                foreach (int value in intValues)
                {
                    if (value > max)
                        max = value;
                }
                for (int i = 1; i <= max; i++)
                {
                    dataGridView2.Columns.Add($"Test{i}", $"Donnée de mesure {i}");
                    foreach (DataGridViewRow row in dataGridView2.Rows)
                    {
                        row.Cells[$"Test{i}"].Style.BackColor = System.Drawing.Color.Gray;
                        row.Cells[$"Test{i}"].ReadOnly = true;


                    }


                }


                int k = 0;

                foreach (DataGridViewRow row in dataGridView2.Rows)
                {

                    if (!(row.Cells[$"{comboBox1.Text + comboBox2.Text}DataGridViewTextBoxColumn"].Value?.ToString() is ""))
                    {


                        try
                        {
                            for (int j = 1; j <= intValues[k]; j++)
                            {
                                row.Cells[$"Test{j}"].Style.BackColor = System.Drawing.Color.White;
                                row.Cells[$"Test{j}"].ReadOnly = false;
                            }
                        }
                        catch (Exception ex)
                        {
                            Debug.WriteLine(ex.ToString());
                        }

                        k++;
                    }
                }

                dataGridView2.Columns.Add("a0", "Jugement OK");
                dataGridView2.Columns.Add("a1", "Jugement Non OK");
                dataGridView2.Columns.Add("a2", "Double contrôle valeur");
                dataGridView2.Columns.Add("a3", "Double contrôle OK/NOK");


                dataGridView1.Rows.Clear();
                dataGridView1.Columns.Clear();
                dataGridView1.Columns.Add("a4", "N°Etiquette");
                dataGridView1.Columns.Add("a5", "Etiquette Emballage C");
                dataGridView1.Columns.Add("a6", "Etiquette Emballage nonC");
                dataGridView1.Columns.Add("a7", "Contrôle visuel C");
                dataGridView1.Columns.Add("a8", "Contrôle visuel non C");
                dataGridView1.Columns.Add("a9", "N° Rapport SIIC");
                dataGridView1.Columns.Add("a10", "Etat de de distribution");
                dataGridView1.Columns.Add("a11", "OK/NOK");


            }

                for (int i = 0; i < t; i++)
                {

                    dataGridView1.Rows.Add();

                }
                
                
                foreach(DataGridViewRow row in dataGridView2.Rows)
                {
                    if(row.Cells["toleranceMinDataGridViewTextBoxColumn"].Value?.ToString() is "")
                    {
                        var cell = (DataGridViewTextBoxCellEx)row.Cells["toleranceMinDataGridViewTextBoxColumn"];
                        string a = row.Cells["toleranceNomDataGridViewTextBoxColumn"].Value?.ToString();
                        cell.ColumnSpan = 3;
                        cell.Value = "";

                        cell.Value = a;
                        cell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
                    }
                }



            dataGridView2.Columns["toleranceMinDataGridViewTextBoxColumn"].ReadOnly = true;
            dataGridView2.Columns["toleranceNomDataGridViewTextBoxColumn"].ReadOnly = true;
            dataGridView2.Columns["toleranceMaxDataGridViewTextBoxColumn"].ReadOnly = true;




        }

解決策 1

まず、文字列を連結して SQL コマンドを作成しないでください。 偶発的または意図的な SQL インジェクション攻撃にさらされ、データベース全体が破壊される可能性があります。 代わりに常にパラメータ化されたクエリを使用してください。

文字列を連結すると、SQL が次のようなコマンドを受け取るため、問題が発生します。

SQL
SELECT * FROM MyTable WHERE StreetAddress = 'Baker's Wood'

SQL に関する限り、ユーザーが追加した引用符によって文字列が終了するため、問題が発生します。 しかし、さらに悪化する可能性もあります。 代わりに「x’;DROP TABLE MyTable;–」と入力すると、SQL はまったく異なるコマンドを受け取ります。

SQL
SELECT * FROM MyTable WHERE StreetAddress = 'x';DROP TABLE MyTable;--'

SQL では、次の 3 つの個別のコマンドとして認識されます。

SQL
SELECT * FROM MyTable WHERE StreetAddress = 'x';

完全に有効な SELECT

SQL
DROP TABLE MyTable;

完全に有効な「テーブルの削除」コマンド

SQL
--'

それ以外はすべてコメントです。
つまり、一致する行を選択し、DB からテーブルを削除し、それ以外は無視します。

したがって、常にパラメータ化されたクエリを使用してください。 または、DB をバックアップから頻繁に復元できるように準備してください。 バックアップは定期的に取っていますよね?
コンボ ボックスがユーザー編集可能でない場合は、現時点では問題なくできるかもしれませんが、6 か月後に誰かが変更を要求したときに、そのコードを覚えているでしょうか? 常にパラメータを使用してください。

第二に、DB がなければ、コードの塊を実行して何が起こっているのかを解明することはできません。すべての「マジック文字列」を含むデータの依存関係が多すぎるため、複製に使用できません。あなたの問題。

それはあなた次第です。
幸いなことに、何が起こっているかを調べるのに役立つツール、デバッガーが利用可能です。 使い方がわからない場合は、Google で「Visual Studio デバッガー」を検索すると必要な情報が得られます。

関数の最初の行にブレークポイントを設定し、デバッガーでコードを実行します。 次に、コードとデータを調べて、手動で何が起こるかを考えます。 次に、各行を 1 ステップずつ実行して、期待したことが実際に起こったかどうかを確認します。 そうでない場合は、問題が発生しているときなので、前に戻って (またはもう一度実行して詳しく調べて) 理由を調べることができます。

申し訳ありませんが、私たちはそれを行うことはできません。新しい (そして非常に便利な) スキルであるデバッグを学ぶ時期です。

コメント

タイトルとURLをコピーしました