DataGridView 行错误索引超出范围 c#

DataGridView Rows Error Index Out of Range c#

我正在使用 C# WinForms,其中有一些复选框,单击按钮后,其文本将添加到 datagridview (dgData) 中。这是它的代码。

private void btnAdd_Click(object sender, EventArgs e)
    {
        dgData.Rows.Clear();
        foreach(Control c in pnlDeficiency.Controls)
        {
            if ((c is CheckBox) && ((CheckBox)c).Checked)
            dgData.Rows.Add(c.Text);
        }
    }

我的保存码在这里。

private void btnSave_Click(object sender, EventArgs e)
    {
        if (MessageBox.Show("Are You Sure You Want to Save the Record!", "TAC | Question", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == DialogResult.Yes)
        {
            SqlConnection S_Conn = new SqlConnection(strConnString);
            S_Conn.Open();
            int a = 10;
            for (int i = 0; i <= dgData.Rows.Count; i++)
            {
                string Query_Insert = "";
                Query_Insert = "INSERT into Deficiency_Details (Vendor_Id, Tender_Id, DeficiencyType) values ('" + cmbSelectVendor.SelectedValue + "', '" + cmbSelectTender.SelectedValue + "', '" + dgData.Rows[i].Cells[0].Value.ToString() + "')";
                SqlCommand Command_Insert = new SqlCommand(Query_Insert, S_Conn);
                a = Command_Insert.ExecuteNonQuery();
            }
            if (a == 0)
            {
                MessageBox.Show("Record Not Saved Successfully! Please Check Fields", "TAC | Alert", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
            }
            else
            {
                MessageBox.Show("Record Saved Successfully", "TAC | Success", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
            }
            S_Conn.Close();
            S_Conn.Dispose();
            ResetAll();
        }
    }

我得到的错误是索引超出范围。我调试了我的程序,错误在这一行

dgData.Rows[i].Cells[0].Value.ToString()

VALUE 变为 NULL。我知道这个错误并且我之前已经解决了很多次但是这次它根本没有解决。请帮助我。

问题出在这一行:

for (int i = 0; i <= dgData.Rows.Count; i++)

你需要改成这样:

for (int i = 0; i < dgData.Rows.Count; i++)

因为假设您的 GridView 中有 10 行。 dgData.Rows.Count 将是 10。现在你 运行 从 0 到 10 因为你的 <= 运算符。 0-10 将是 11 个循环 运行nings。您的 GridView 仅包含 10 行。所以索引超出了你最后一次循环迭代的范围。如果您更改为 < 运算符,您的循环只是 运行ning 从 0-9 正好是 10 次迭代。

使用下面的代码,您可以指定要插入的单元格的索引

DataGridViewRow row = (DataGridViewRow)dgData.Rows[0].Clone();
row.Cells[0].Value = c.text;
dbData.Rows.Add(row);