【发布时间】:2020-05-27 11:59:31
【问题描述】:
我一直在尝试创建一个 Windows 窗体应用程序,在满足某些条件后我以编程方式创建一个 TextBox。但是,当我运行代码时,由于某种原因,代码就像没有 if 语句一样工作。我尝试添加更多条件来防止这种情况发生,并且我还尝试查看是否有任何条件在应该为假时被发现为真。我不知道该怎么办。这是我的代码:
private void fmaEquation(object sender, EventArgs e)
{
// get whether any textboxes hold any of these strings
bool f = IfVarIsThere("f");
bool m = IfVarIsThere("m");
bool a = IfVarIsThere("a");
// if textbox has not been added but 2 of 3 variables are given
Console.WriteLine("F: " + f + " M: " + m + " A: " + a + " eqNum: " + eqNum + " Contains? " + this.Controls.Contains(eq[eqNum]));
if (!(this.Controls.Contains(eq[eqNum])) && ((f && m) || (m && a) || (f && a)))
{
eq[eqNum] = new TextBox();
eq[eqNum].Location = new System.Drawing.Point(10 + 3 * txtSize, 30 + eqNum * 20);
eq[eqNum].Size = new System.Drawing.Size(txtSize, 10);
this.Controls.Add(eq[eqNum]);
eq[eqNum].Text = "f = m * a";
}
// else, if the textbox is there, but 2 of 3 variables are not there
else if ( !((f && m) || (m && a) || (f && a)) && this.Controls.Contains(eq[eqNum]))
{
this.Controls.Remove(eq[eqNum]);
}
}
private bool ifVarIsThere(String s) // loop through array to see whether String s is in any of the variable textboxes
{
for (int i = 0; i < varNum; i++)
{
if (var[i].Text.ToLower() == s)
{
return true;
}
}
return false;
}
由于某种原因,文本框会添加自己,然后删除自己,然后重新添加自己并以永无止境的循环重复。我也在后台运行这个方法。
【问题讨论】:
-
文本框不会像那样对自己“做”任何事情。代码对文本框做了什么?我怀疑“添加”和“删除”调用是相关的..
-
@user2864740 ,我同意。问题可能来自“添加”和“删除”调用。
-
对不起,我的错误。 Windows 窗体应用程序不断重新添加和删除文本框。 this.Controls.Add(Control) 将该控件添加到列表中。 this.Controls.Contains(Control object) 将确定 Control 是否在列表中。 this.Controls.Remove(Control) 将从列表中删除该控件。我希望这会有所帮助!
-
我通过替换 else if ( !((f && m) || (m && a) || (f && a)) && this.Controls.Contains(eq[eqNum])) 进行了检查与 else if (!(f && m)) 但没有任何改变
-
eq eqNum 和 var 是什么意思?