I'm stucked with a System.NullReferenceException when I'm trying to delete the lonely row of a datatable, displayed in a datagridview by using a button click. This datatable is within a dataset, who's generated from XLM schema and XML file. But, if I have more than 1 line in this datatable, I can delete the selected one without throwing any exception.
I explored a lot of posts on stackoverflow but anyone of them could help me !
I give you the portion of code who's throwing the exception :
private void button4_Click(object sender, EventArgs e)
{
DialogResult removeLocationChoice = MessageBox.Show("Are you sure you want to delete this location ?", "Remove location ?", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (removeLocationChoice == DialogResult.Yes)
{
// Get the index of the currentrow from datagridview1
int currentIndex = (this.dataGridView1.CurrentRow.Index);
// Remove the selected row into the dataset
Functions.settingsDataSet.Tables["Location"].Rows[currentIndex].Delete();
// Commit changes to dataset
Functions.settingsDataSet.Tables["Location"].AcceptChanges();
// Commit changes from dataset to XML file
Functions.commitXml();
}
}
FYI I use Visual Studio 2010.
I found these strange values with the debugger :
Functions.settingsDataSet.Tables["Location"].Rows[currentIndex].newRecord = -1
.RowState = Detached
Don't hesitate to ask me for more information and other portions of code. I suspect an error due to headers but I'm not sure about that.
Ok so new update : I found a solution but not the best ! I remove my table form the dataset and then I reapply the XML schema to recover my table without any rows :
public static void removeRow(string table, int row)
{
if (row == 0)
{
settingsDataSet.Tables.Remove(table);
settingsDataSet.ReadXmlSchema(settingsSchema);
settingsDataSet.AcceptChanges();
}
else
{
settingsDataSet.Tables[table].Rows.RemoveAt(row);
settingsDataSet.Tables[table].AcceptChanges();
}
commitXml();
}
By this way I don't have any exception any more. If you have better solution, please comment or reply on this post !! :-)