我有一本字典,
private Dictionary<int, int> dict = new Dictionary<int, int>();
我调用foreach循环来遍历我的dataTable并填充字典,
foreach (DataRow row in SubVwr.Tables[0].Tbl.Rows)
{
dict.Add(Convert.ToInt32(row["ItemNo"]), (int)row["QtyRcvd"]);
}
稍后,在另一种方法中,我想使用以下代码从我的字典中回忆一些值
int QtyChanged = (int)row["QtyRcvd"] - dict[Convert.ToInt32(row["ItemNo"])];
这会引发异常,因为字典“没有那个值”。我已经尝试在添加之后打印出字典中的所有值,并且它就在那里。但是当我尝试在上面的其他方法中调用它之前打印它时,它不会打印任何东西。因为据说它是空白的。有没有人看到我没看到的事情是怎么回事?
这些方法是由一个wpf按钮驱动的,在mvvm系统中这都发生在相应的viewmodel中
private void ReceiveOrder(object sender)
{
//log each QtyRcvd for later comparison
foreach (DataRow row in SubVwr.Tables[0].Tbl.Rows)
{
dict.Add(Convert.ToInt32(row["ItemNo"]), (int)row["QtyRcvd"]);
Console.Out.WriteLine(dict[Convert.ToInt32(row["ItemNo"])]);
}
foreach (KeyValuePair<int, int> kvp in dict)
{
//textBox3.Text += ("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
Console.Out.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
}
ReceiveOrderDialogWindow dialog = new ReceiveOrderDialogWindow()
{
Topmost = true
};
dialog.ShowDialog();
}
第二次调用,在ReceiveOrderDialogWindow
中单击一次按钮 private void requestSerials(object sender)
{
CommandsViewModel commands = new CommandsViewModel(new ModulesViewModel());
//for each row in our received order..
foreach (DataRow row in SubVwr.Tables[0].Tbl.Rows)
{
foreach (KeyValuePair<int, int> kvp in dict)
{
//textBox3.Text += ("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
Console.Out.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
}
int QtyChanged = (int)row["QtyRcvd"] - dict[Convert.ToInt32(row["ItemNo"])];