Search code examples
c#xmldatagridviewdelete-row

Delete multiple rows from data grid view


I'm trying to delete multi rows from data grid view in c# I use xml file as a database.

Here is my code; when I trying to delete in the data grid view, they are deleted correctly, but in the XML file, just the last selected row is deleted, and the sequence row after it.

var selectedRows = CustomersInformation.SelectedRows
          .OfType<DataGridViewRow>()
          .Where(row => !row.IsNewRow)
          .ToArray();

foreach (var row in selectedRows)
{
    XDocument Customersdocument = XDocument.Load(@"customers.xml");
    var DeleteQuery = Customersdocument.Descendants("Customer")
                .Where(del => del.Element("PhoneNumber").Value ==
                CustomersInformation.CurrentRow.Cells[1].Value.ToString());

    DeleteQuery.Remove();

    Customersdocument.Save(@"customers.xml");
    CustomersInformation.Rows.Remove(row);

    CustomersInformation.ClearSelection();
} 

My XML file looks like this but with more customers

<Customers>
    <Customer>
        <Name>sara</Name>
        <PhoneNumber>7176665</PhoneNumber>
        <BirthDate>12/28/2000</BirthDate>
        <ExpireDate>2023-03-28T09:15:27.8040881+03:00</ExpireDate>
        <PackageId>1</PackageId>
        <Balance>8</Balance>
    </Customer>
</Customers>

Solution

  • The main problem is this line:

    CustomersInformation.CurrentRow.Cells[1].Value.ToString());
    

    The keyword:

    ...CurrentRow...
    

    acts differently than what you're trying to loop through all the rows in datagridview.

    you're trying to do a "foreach" loop, but getting the values from "currentrow".

    if you performs a

    CustomersInformation.ClearSelection();
    

    The "currentrow" will become "null".

    So, u can do this, load the xml first, before the loop:

    XDocument Customersdocument = XDocument.Load(@"customers.xml");
    
    foreach (var row in selectedRows)
    {
        // remove row
    }
    
    // save the file after the loop finished
    Customersdocument.Save(@"customers.xml");
    

    in the loop:

    foreach (var row in selectedRows)
    {
        // get da phoneNumber from foreach row, not currentrow
        var phoneNumber = row.Cells[1].Value.ToString();
    
        // not from currentrow
        //var phoneNumber = CurrentRow.Cells[1].Value.ToString();
    
        // generate delete query
        var DeleteQuery = Customersdocument.Descendants("Customer")
        .Where(del => del.Element("PhoneNumber").Value == phoneNumber);
    
        // do remove
        DeleteQuery.Remove();
    
        // remove from teh datagridview
        CustomersInformation.Rows.Remove(row);
    }