Reputation: 145
I got an Exception here that doesn't find the rootPartNo
key in unbreakableLinkMap
dictionary.
MyTree<IDbRecord> currentTree = PartHelper.GetTreeForRootId(succesorId, graph);
#region TreeSheet
string rootPartNo = currentTree.Root.Payload.GetField(Part.c_partNo).GetString();
//get spirit links
var spiritLinks = graph.unbreakableLinkMap[rootPartNo];
Worksheet treeWS = excel.Worksheets[2];
treeWS.Name = "Tree";
long displayedPartId = long.Parse(GetIdFromSession(Part.t_name));
int rowNo = 0;
bool bold = false;
Color color = Color.Black;
foreach (MyTreeNode<IDbRecord> node in currentTree.Root.DepthFirstNodeEnumerator)
{
string partNo = node.Payload.GetField(Part.c_partNo).GetString();
treeWS.Cells[rowNo, node.Depth].PutValue(partNo);
bold = false;
color = Color.Black;
if (spiritLinks.Find(suc => suc.PartNo == partNo || suc.SucPartNo == partNo) != null)
{
color = Color.Red;
}
if (node.Payload.GetField(Part.c_id).GetInt64() == displayedPartId)
{
bold = true;
}
headerFStyle.Font.IsBold = bold;
headerFStyle.Font.Color = color;
treeWS.Cells[rowNo, node.Depth].SetStyle(headerFStyle);
rowNo++;
}
How can I check/validate this?
Upvotes: 0
Views: 1484
Reputation: 16956
Usually you get this exception when the key specified for accessing an element in a collection does not match any key in the collection.
I would suggest use the debugger and see you have that Key
available in the Dictionary
If you are unsure of key existence, I would suggest writing defensive code, using ContainsKey
or TryGetValue
.
if (graph.unbreakableLinkMap.ContainsKey(key))
{
...
}
or
if (graph.unbreakableLinkMap.TryGetValue(key, out spiritLinks)) {}
Upvotes: 4
Reputation: 186688
Well, you have to debug. Put a breakpoint on the
var spiritLinks = graph.unbreakableLinkMap[rootPartNo];
line, run the routine and inspect the values of question:
rootPartNo
as well as dictionary keys
graph.unbreakableLinkMap.Keys
If you can't use debugger for whatever reason, add debug output
...
string rootPartNo = currentTree.Root.Payload.GetField(Part.c_partNo).GetString();
// Debug output: when key is not found, show additional info
if (!graph.unbreakableLinkMap.ContainsKey[rootPartNo])
MessageBox.Show(String.Format(
"Key to find is \"{0}\" and keys in the dictionary are\r\n{1}",
rootPartNo,
String.Join(", ", graph.unbreakableLinkMap.Keys)));
...
Upvotes: 0