for (int j = 0; j < dataGridView2.Rows.Count; j++)
{
if (dataGridView2.Rows[j].Cells[1].Value.ToString() != dataGridView2.Rows[j+1].Cells[1].Value.ToString())
{
MessageBox.Show(dataGridView2.Rows[j].Cells[2].Value.ToString() + "有重复");
return;
}
}当发现有重复数据的时候 没问题
但是 没重复数据的时候 就提示索引超出范围我想请教下,在不改变思路的情况下 如何改下代码 解决问题!
新手分少
{
for (int j = 0; j < dataGridView2.Rows.Count; j++)
{
if (dataGridView2.Rows[j].Cells[1].Value.ToString() != dataGridView2.Rows[j+1].Cells[1].Value.ToString())
{
MessageBox.Show(dataGridView2.Rows[j].Cells[2].Value.ToString() + "有重复");
return;
}
}
}
for (int j = 0; j < dataGridView2.Rows.Count - 1; j++) { if (dataGridView2.Rows[j].Cells[1].Value.ToString() != dataGridView2.Rows[j+1].Cells[1].Value.ToString()) { MessageBox.Show(dataGridView2.Rows[j].Cells[2].Value.ToString() + "有重复"); return; } }问题在于你的Rows[j+1],你的循环应该 - 1
return;
{
// 判断
if(dataGridView2.Rows[j].Count <= j+1) continue; if (dataGridView2.Rows[j].Cells[1].Value.ToString() != dataGridView2.Rows[j+1].Cells[1].Value.ToString())
{
MessageBox.Show(dataGridView2.Rows[j].Cells[2].Value.ToString() + "有重复");
return;
}
}
1.你是要找重复数据,所以不能只能拿当前的和它下一个比,这样肯定不全面。比较的时候思路这样可能会合理一点:每次比较的时候都要拿当前的和下面所有的比,因此这是一个两层的循环。
2.如果是业务需要就是要比较当前行和下行,那么你可以从0开始比到<leng - 1就可以了,或者<leng - 2。
{
for(int k = j; k < dataGridView2.Rows.Count - 1; k++)
{
if (dataGridView2.Rows[j].Cells[1].Value.ToString() != dataGridView2.Rows[k].Cells[1].Value.ToString())
{
MessageBox.Show(dataGridView2.Rows[j].Cells[2].Value.ToString() + "有重复");
return;
}
}
}2.原有思路实现:for (int j = 0; j < dataGridView2.Rows.Count - 1; j++)
{
if (dataGridView2.Rows[j].Cells[1].Value.ToString() != dataGridView2.Rows[j+1].Cells[1].Value.ToString())
{
MessageBox.Show(dataGridView2.Rows[j].Cells[2].Value.ToString() + "有重复");
return;
}
}注意到一点,你在判断的时候用“!=”来判断是有重复的,是不是反了?
{
for(int k = j; k < dataGridView2.Rows.Count; k++)
{
if (dataGridView2.Rows[j].Cells[1].Value.ToString() != dataGridView2.Rows[k].Cells[1].Value.ToString())
{
MessageBox.Show(dataGridView2.Rows[j].Cells[2].Value.ToString() + "有重复");
return;
}
}
}