DataGridViewRow索引在刷新时超出范围异常

时间:2014-12-15 18:00:21

标签: c# datagridview refresh indexoutofrangeexception

我的C#应用​​程序中有一个数据网格视图。当我突出显示该行并且我点击删除时,该行将被删除,但是当我运行更新和刷新命令时,我得到一个超出范围异常的索引

private void btnDeleteMember_Click(object sender, EventArgs e)
{
    foreach (DataGridViewRow item in this.dgvAllFaculty.SelectedRows)
    {
        int row = item.Index;
        FacultyMember member = memberList[row];

        if (row >= 0)
        {
            memberList.RemoveAt(row);

            Save();
            this.dgvAllFaculty.Update();
            this.dgvAllFaculty.Refresh();
            return;
        }

     }
}

调试时我注意到它在刷新调用时失败。我得到的错误是

System.IndexOutOfRangException: Index 1 does not have a value
  at System.Windows.Forms.CurrencyManager.get_Item(Int32 index)
  at
System.Windows.Forms.DataGridView.DataGridViewDataConnection.GetError(Int32 rowIndex)

如果还有别的东西需要让我知道。我想知道当刷新发生它的疯狂原因时,它仍然认为第二行是否存在?

1 个答案:

答案 0 :(得分:0)

好的,我改变了我的代码,现在正在运行。在刷新之前,我必须先从json文件重新加载数据。

private void btnDeleteMember_Click(object sender, EventArgs e)
    {
        int count = this.dgvAllFaculty.SelectedRows.Count;

        foreach (DataGridViewRow item in this.dgvAllFaculty.SelectedRows)
        {
            int i = item.Index;
            FacultyMember member = memberList[i];
            memberList.RemoveAt(i);
            Save();
        }

        if (count > 1)
        {
            MessageBox.Show(String.Format("{0} faculty memebers deleted", count));
        }
        else
        {
            MessageBox.Show("Faculty Member Deleted");
        }

        // Load the newest data from file before refreshing the view
        ViewAll_Load(sender, e);
        this.Refresh();
    }