更新数据时,如何在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更新所有值.
I have GridView and I need HTML ENCODE all values being update using Event handler _RowUpdating.
此刻我使用此脚本但收到错误:
At the moment I use this script BUT I receive an error:
Collection was modified; enumeration operation may not execute.
有人知道如何使它起作用吗?感谢您的帮助!
Any idea how to make it works? Thanks for your help!
foreach (DictionaryEntry entry in e.Keys)
{
e.Keys[entry.Key] = Server.HtmlEncode(entry.Value.ToString());
}
推荐答案
三个选项:
1)首先获取所有条目的副本,这样您实际上就不会遍历这些条目并随时进行修改.
1) Take a copy of all the entries to start with, so you're not actually iterating over those and modifying them as you go.
2)再次遍历键的副本-避免修改正在遍历的内容.
2) Just iterate over a copy of the keys - again, to avoid modifying what you're iterating over.
3)构建新词典,而不要修改现有词典.
3) Build a new dictionary instead of modifying the existing one.
在此处给出基本代码:
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):
... and taking "upper-casing" as a simple thing to test (just use Server.HtmlEncode
in your real code), here are the three options (I'm assuming you have LINQ available to you):
1)遍历条目的副本:
1) Iterating over a copy of the entries:
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
变量):
3) Creating a new dictionary (and then assigning the reference back to the dict
variable):
dict = dict.ToDictionary(entry => entry.Key,
entry => entry.Value.ToUpperInvariant());
这篇关于更新数据时,如何在GridView中使用HTML ENCODE值-错误:集合已修改;枚举操作可能无法执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!