简体   繁体   English

Datagrid在删除行

[英]Datagrid in delete the row

I am using delete row index to delete a row in datagridview. 我正在使用删除行索引删除datagridview中的行。

But when one row is deleted then datagridview automatically appends next row 但是当删除一行时,datagridview会自动附加下一行

first time any index is deleted then itscorrect but at the second time row-1 indexed row is deleted 第一次删除任何索引,然后删除它,但第二次删除第1行索引行

I am using this code: 我正在使用此代码:

for (int i = 0; i < path.Length; i++)
{
    lpath.Add(path[i].ToString());
    dataGridView1.Rows.RemoveAt(int.Parse(arr[i]));
}

you have to reduce the 'i' after you delete a row when using for loop 使用for循环删除行后,必须减少'i'

See the following code 请参阅以下代码

 for (int i = 0; i < path.Length; i++)
{
   lpath.Add(path[i].ToString());
  dataGridView1.Rows.RemoveAt(int.Parse(arr[i]));
  i--;  }

it's a bit weird to increase i within the for loop than decrease it. for循环中增加i比减少它有点奇怪。 Why don't you add the items than clear all rows ? 为什么不添加项目而不是清除所有行?

for (int i = 0; i < path.Length; i++) {
    lpath.Add(path[i].ToString());
}
dataGridView1.Rows.Clear();

As i see it you skew the index off the dataGridView1 the first time. 正如我所看到的那样,你第一次将索引从dataGridView1歪斜了。

lets say you have a list with element {1,2,3,4,5} if we now remove index 3 and then 4 we the end up removing 3 and 5 giving us the list {1,2,4} but we wanted to remove 3 and 4 not 3 and 5 假设你有一个元素{1,2,3,4,5}的列表,如果我们现在删除索引3然后4我们最终删除3和5给我们列表{1,2,4}但我们想要删除3和4而不是3和5

what i think you want to do is to get all indexes you want to remove, and the order them and remove from top to bottom so instead of removing 3 an 4 in that order you remove 4 and 3 giving us the list {1,2,5} 我认为你想要做的是获取你想要删除的所有索引,并对它们进行排序并从上到下删除,而不是按顺序删除3和4,删除4和3给我们列表{1,2,5}

List<int> RemoveList = new List<int>();
for (int i = 0; i < path.Length; i++)
{
    lpath.Add(path[i].ToString());
    RemoveList.Add(int.Parse(arr[i]));
}

//Remove highest index first.
RemoveList.OrderByDescending(a=>a);
for (int i = 0; i < RemoveList.Count; i++)
{
    dataGridView1.Rows.RemoveAt(RemoveList[i]);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM