The OrderedDictionary is read only and cannot be modified
Q:
When i try the following code :
((IOrderedDictionary)Session["keys"])[2] = objToUpdate.Note_title;
((IOrderedDictionary)Session["keys"])[3] = objToUpdate.Iscourse;
It throws an exception:
The OrderedDictionary is read only and cannot be modified.
My question:
- Why just read only?
- How to set my key in the session,fixing my problem?
EDIT:
I fill the IOrderedDictionary
through this:
IOrderedDictionary keys = gv_co开发者_如何学编程urses.DataKeys[index].Values;
Session["Keys"] = keys;
Brute force solution is to copy values to new dictionary before saving to session:
IOrderedDictionary orderedDictionary = new OrderedDictionary();
foreach (KeyValuePair<TKey, TValue> kvp in gv_courses.DataKeys[index].Values)
{
orderedDictionary.Add(kvp.key, kvp.value);
}
Session["Keys"] = keys;
However, I strongly recommend to find another way to get your keys without using DataKeys property of your GridView.
- Why just read only?
The code gives the read only error because the reference in Session["Keys"] point to gv_courses.DataKeys[index].Values which is read only. The entire DataKeyArray Datakeys is read only and also the Values property of each of his DataKey element. From what i read on the internet this is a .net design choice and it is probably read only so it stays in sync with the datasource (if you could modify the DataKeyArray it would have to propagate to the datasource).
- How to set my key in the session,fixing my problem?
What you need to do is make a deep copy of gv_courses.DataKeys[index].Values and then save that new copy in Session["keys"]. For example:
IOrderedDictionary keys = gv_courses.DataKeys[index].Values;
var keysTemp = new OrderedDictionary();
foreach (DictionaryEntry de in keys)
{
keysTemp.Add(de.Key, de.Value);
}
The keys OrderedDictionary is the same as gv_courses.DataKeys[index].Values but it doesn't have read only. So now you can save it to the session:
Session["KeysCourse"] = keysTemp; //keysTemp is equal to keys but is editable
And now the code will run since the OrderedDictionary in Session is no longer read only:
((IOrderedDictionary)Session["KeysCourse"])[2] = objToUpdate.Note_title;
((IOrderedDictionary)Session["KeysCourse"])[3] = objToUpdate.Iscourse;
I reach what i want to do ,thanks for all replies ..
IOrderedDictionary keys = gv_courses.DataKeys[index].Values;
string[] keysTemp = new string[4];
keysTemp[0] = keys[0].ToString();
keysTemp[1] = keys[1].ToString();
keysTemp[2] = keys[2].ToString();
keysTemp[3] = keys[3].ToString();
Session["KeysCourse"] = keysTemp;
Then
((string[])Session["KeysCourse"])[2] = objToUpdate.Note_title;
((string[])Session["KeysCourse"])[3] = objToUpdate.Iscourse.ToString();
精彩评论