DataGridView行错误索引超出范围c# [英] DataGridView Rows Error Index Out of Range c#
问题描述
我正在使用C#WinForms,其中有一些复选框,单击按钮时其文本将添加到datagridview(dgData)中.这是它的代码.
I am working on C# WinForms where i have some checkboxes, whose text are added in datagridview (dgData) on a button click. Here is its code.
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();
}
}
我得到的错误是索引超出了范围.我已经调试了程序,错误在这一行
The error i get is Index out of rannge. I have debugged my program and the error is in this line
dgData.Rows[i].Cells[0].Value.ToString()
其中VALUE变为NULL的位置.我知道该错误,我之前已经解决了很多次,但这一次根本没有解决.请帮助我.
Where VALUE is going NULL. I know the error and i solved it many times before but this time its not solving at all. please help me.
推荐答案
问题是此行:
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次循环运行.您的GridView仅包含10行.因此,索引在您上一次循环迭代时超出范围.如果更改为<运算符,您的循环仅从0-9开始运行,这恰好是10次迭代.
Because let's say you got 10 Rows in your GridView. dgData.Rows.Count would be 10. Now you run from 0 to 10 because of your <= Operator. 0-10 would be 11 loop runnings. Your GridView only contains 10 rows. So the Index is out of range on your last loop iteration. If you change to < Operator your loop is just running from 0-9 which are exactly 10 iterations.
这篇关于DataGridView行错误索引超出范围c#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!