[英]Deleting rows from DataTable gives “String binding is invalid”
我有一個填充有值的DataTable,其中之一是DateTime。 我希望根據刪除所有早於“ spotTime”的條件的標准從該表中刪除行。 問題是它的動作似乎不一致,並且如果我打開VS調試器,則會收到錯誤消息,指出字符串綁定無效。 如果我嘗試在調試模式下工作,則程序會因該錯誤而關閉,並且永遠不會到達catch語句。 但是,以非調試模式運行時,似乎並不總是刪除行。 我嘗試了一些方法,但似乎無法正常工作。 這是代碼。 這是一個每分鍾觸發一次的計時器。
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)
{
}
}
刪除dt.Rows [i] .Delete()可以消除錯誤,但是當然我沒有得到所需的東西。 我一定做錯了,但是似乎無法調試它。 有什么建議么? 謝謝湯姆
當您嘗試在循環中從循環中刪除元素時,循環往往會變得非常煩躁。 您可以嘗試將計數變成一個獨立的整數,然后以相反的順序遍歷循環,以便在刪除內容時不會對計數產生不利影響。 例如:
int counter = dt.Rows.Count; for (var i = counter-1; i >= 0; i--) { ... the rest of your code }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.