我有一个文本框的字典,我正用于我的程序。更改选项时,我希望删除这些框,以便为下一页创建新框。
public static bool command0 () {
foreach (TextBox tBox in Globals.inputBoxes)
tBox = null;
return true;
}
返回此错误
Cannot convert type 'System.Collections.Generic.KeyValuePair<string,System.Windows.Forms.TextBox>' to 'System.Windows.Forms.TextBox' (CS0030) - C:\Users\e309706\Documents\SharpDevelop Projects\simulator 3\simulator 3\Globals.cs:73,4
有没有一种简单而正确的方法来做我想做的事情?
答案 0 :(得分:3)
您的Globals.inputBoxes
是一本字典,因此它们将遍历键值对。将代码调整为:
// This kvp variable is what your exception is saying was wrong.
foreach (KeyValuePair<string, TextBox> kvp in Globals.inputBoxes)
{
Textbox txt = kvp.Value;
// Do what you need to with the txt object now
}
修改强>
还有另一种方法可以做到这一点,正如一些人所建议的那样:
foreach (TextBox txtin Globals.inputBoxes.Values)
{
// Do what you need to with the txt object now
}
关于这个额外方法的事情是,很多时候,你也可能想要在循环中使用字典中的键。只重复这些值将不允许您在不再次访问字典的情况下访问它。