简体   繁体   中英

How to detect only the latest changed datarow to reject changes?

In my DataTable the latest row which was changed by the user shall be rejected. My code rejects always in the same order. If the user changes the first row first and after that changes the third row, the program should reject the third row first, but it rejects the first row instead. Do you have any idea, how I can detect the correct order of changed rows?

   public void UndoChanges()
    {                    
        foreach (DataRow dr in MyTable.Rows)
        {                
            if (dr.RowState != DataRowState.Unchanged)                
            {
                dr.RejectChanges();
                return;
            }
        }
    }

This is my final solution: The DataTable listens to the RowChanged Event. I put the modified row into a list. Thanks to jdweng and Tim Schmelter .

    private DataTable dt;
    public List<DataRow> ModifiedRowsList { get; private set; }

    public myClass()
    {
        dt = new DataTable();
        dt.RowChanged += new DataRowChangeEventHandler(Row_Changed);
        ModifiedRowsList = new List<DataRow>();
    }

    public void UndoChanges()
    {
        if (ModifiedRowsList.Count > 0)
        {
            DataRow dr = dt.Rows[dt.Rows.IndexOf(ModifiedRowsList[ModifiedRowsList.Count - 1])];

            dr.RejectChanges();

            ModifiedRowsList.RemoveAt(ModifiedRowsList.Count - 1);
        }
    }

    private void Row_Changed(object sender, DataRowChangeEventArgs e)
    {
        if(e.Action != DataRowAction.Rollback)
        {
            ModifiedRowsList.Add(e.Row);
        }          
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM