0

I get an array index out of range exception when removing the last row in a datatable in WPF. Removing other rows is ok, but trying to remove the last row triggers this problem. What is wrong here?

public void removeRow(int index)
{
    if (index < 0)
    {
        index = 0;
    }
    myDataTable.Rows.RemoveAt(index);
    myDataTable.AcceptChanges();
}

I also tried selectedDataRow.delete() and myDataTable.remove(selectedDataRow) but they have the same problem.

Michael0x2a
  • 58,192
  • 30
  • 175
  • 224

1 Answers1

2

The row number is 0 indexed so you are probably off by one. You could add this to your check

if (index < 0)
{
    index = 0;
}
else if (index >= myDataTable.Rows.Count)
{
    index = myDataTable.Rows.Count - 1;
}

When a row is removed, all data in that row is lost. You can also call the Delete method of the DataRow class to just mark a row for removal. Calling RemoveAt is the same as calling Delete and then calling AcceptChanges.

Sam Marion
  • 690
  • 1
  • 4
  • 17
  • thanks for answering. this will not delete the row I want, removes the previous row. I guess the last row is not considered as the datatable row! it is just shown in datagrid. sounds strange! – Armin Javid Sep 18 '17 at 18:29
  • You might be referring to the last blank row to allow users to add rows? https://stackoverflow.com/questions/3665048/how-to-disable-the-last-blank-line-in-datagridview – Sam Marion Sep 18 '17 at 18:31
  • No problem. I still suggest you add the extra validation to the method to prevent future out of range exceptions. – Sam Marion Sep 18 '17 at 18:34