winform界面如下:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Data; 5 using System.Drawing; 6 using System.Linq; 7 using System.Text; 8 using System.Threading.Tasks; 9 using System.Windows.Forms; 10 11 namespace form1 12 { 13 public partial class Form1 : Form 14 { 15 List<Student> data = GetStudents(); 16 public Form1() 17 { 18 InitializeComponent(); 19 20 this.dataGridView1.DataSource = data; 21 } 22 23 24 public static List<Student> GetStudents() 25 { 26 27 return new List<Student>() 28 { 29 new Student{ ID =1,Name="小a",Age=18}, 30 new Student{ ID =2,Name="小b",Age=18}, 31 new Student{ ID =3,Name="小c",Age=18}, 32 new Student{ ID =4,Name="小d",Age=18}, 33 new Student{ ID =5,Name="小e",Age=18}, 34 new Student{ ID =6,Name="小f",Age=18}, 35 new Student{ ID =7,Name="小g",Age=18}, 36 new Student{ ID =8,Name="小k",Age=18} 37 38 }; 39 40 } 41 private void tsmDelete_Click(object sender, EventArgs e) 42 { 43 44 List<Student> students = new List<Student>(); 45 foreach (DataGridViewRow row in this.dataGridView1.SelectedRows) 46 { 47 var student = row.DataBoundItem as Student; 48 if (student != null) 49 { 50 data.Remove(student); 51 // students.Add(student); 52 } 53 } 54 55 for (int i = 0; i < students.Count(); i++) 56 { 57 data.Remove(students[i]); 58 } 59 this.dataGridView1.DataSource = null; 60 this.dataGridView1.DataSource = data; 61 } 62 } 63 }
问题说明:右键删除行的时候异常,System.IndexOutOfRangeException:“索引 7 没有值。
删除的代码如下:
private void tsmDelete_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow row in this.dataGridView1.SelectedRows)
{
var student = row.DataBoundItem as Student;
if (student != null)
{
data.Remove(student);
}
}
this.dataGridView1.DataSource = null;
this.dataGridView1.DataSource = data;
}
修改后的代码:
private void tsmDelete_Click(object sender, EventArgs e)
{
List<Student> students = new List<Student>();
foreach (DataGridViewRow row in this.dataGridView1.SelectedRows)
{
var student = row.DataBoundItem as Student;
if (student != null)
{
students.Add(student);
}
}
for (int i = 0; i < students.Count(); i++)
{
data.Remove(students[i]);
}
this.dataGridView1.DataSource = null;
this.dataGridView1.DataSource = data;
}
异常的原因分析:
this.dataGridView1.SelectedRows获取选中的行,假设删除的是第7行和第8行。
遍历去取删除这两行,类型DataGridViewRow 直接引用数据源中的值。第7行删除以后总行数就变成了7行 row.DataBoundItem去根据索引取第8行的值就超出了索引。