簡體   English   中英

更新數據時,如何在GridView中使用HTML ENCODE值-錯誤:集合已修改; 枚舉操作可能無法執行

[英]How to HTML ENCODE values in a GridView when Updatating - Error: Collection was modified; enumeration operation may not execute

我有GridView,我需要HTML ENCODE使用事件處理程序_RowUpdating更新所有值。

目前,我使用此腳本但收到一個錯誤:

Collection was modified; enumeration operation may not execute.

知道如何使它起作用嗎? 謝謝你的幫助!

       foreach (DictionaryEntry entry in e.Keys)
        {
            e.Keys[entry.Key] = Server.HtmlEncode(entry.Value.ToString());              
        }

三種選擇:

1)首先復制所有條目,因此您實際上並不需要遍歷所有條目並隨時進行修改。

2)只需遍歷的副本-再次避免避免修改要遍歷的

3)建立新字典,而不要修改現有字典。

在此給出基本代碼:

using System;
using System.Collections.Generic;
using System.Linq;

class Test
{    
    static void Main()
    {
        var dict = new Dictionary<string, string>
        {
            { "X", "first" },
            { "Y", "second" },
            { "Z", "third" }
        };

        // INSERT DICTIONARY-CHANGING CODE HERE            

        foreach (var entry in dict)
        {
            Console.WriteLine("{0} = {1}", entry.Key, entry.Value);
        }
    }
}

...並將“大寫字母”作為簡單的測試(只需在實際代碼中使用Server.HtmlEncode ),這是三個選項(我假設您可以使用LINQ):

1)遍歷條目的副本:

    foreach (var entry in dict.ToList())
    {
        dict[entry.Key] = entry.Value.ToUpperInvariant();
    }

2)遍歷密鑰副本:

    foreach (string key in dict.Keys.ToList())
    {
        dict[key] = dict[key].ToUpperInvariant();
    }

3)創建一個新字典(然后將引用分配回dict變量):

    dict = dict.ToDictionary(entry => entry.Key,
                             entry => entry.Value.ToUpperInvariant());

這意味着無法修改您要迭代的項目; 創建新字典並復制其中的項目,然后在完成循環后將其重新設置。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM