简体   繁体   中英

Deleting rows from DataTable gives “String binding is invalid”

I have a DataTable that is filled with values one of which is a DateTime. I wish to delete rows from this table based on a criteria where anything older than "spotTime" is deleted. The problem is that it seems to be inconsistent in it's actions and if I turn on the VS debugger, I get an error that the string binding is invalid. If I try to work in debug mode, the program just closes with that error and never reaches the catch statement. However, running in non-debug mode, it doesn't always seem to delete the rows. I have tried a few approaches and non seem to work right. Here is the code. This is a timer that fires once a minute.

    public void ageTimer_Elapsed(object source, System.Timers.ElapsedEventArgs e)
    {
        try
        {
            spotAge = Convert.ToDouble(Properties.Settings.Default.SpotAge);

            //Select all rows in datatable where the age is older than spotAge and delete them.
            //date is stored in dt as 20:12:2017: 21:49:02 derived from DateTime.UtcNow.ToString("dd:MM:yyyy: HH:mm:ss")

            //spotTime is the time from the table
            DateTime spotTime;

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                spotTime = DateTime.ParseExact(Convert.ToString(dt.Rows[i]["date"]), "dd:MM:yyyy: HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);

                if (spotTime.AddMinutes(spotAge) <= DateTime.UtcNow)
                {
                    dt.Rows[i].Delete();
                }

                else
                {
                    break;
                }
            }

            updateDisplay("");
        }

        catch (Exception x)
        {

        }

    }

Removing the dt.Rows[i].Delete() gets rid of the error but of course then I don't get what I need. I must be doing this incorrectly but I cannot seem to debug it. Any suggestions? Thanks, Tom

Loops tend to get really antsy when you try to delete elements from them while you are looping through. You might try getting the count into an independent integer, and then going through the loop in reverse order so that when you remove things, it isn't affecting the count adversely. For example:

int counter = dt.Rows.Count; for (var i = counter-1; i >= 0; i--) { ... the rest of your code }

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