【问题标题】:Why does the TextBox in visual c# keep removing and adding itself?为什么 Visual c# 中的 TextBox 不断删除和添加自身?
【发布时间】: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 是什么意思?

标签: c# textbox controls


【解决方案1】:

我不知道 Idle 是否是您想要的活动。每当线程进入空闲状态时,空闲就会触发。如果您继续关闭此事件并且表单混乱,它将更改状态然后返回并再次处于空闲状态,从而在您添加控件时导致无限循环。

然后,由于您添加了一个文本框,其字面意思是“f = m + a”,因此下次您将始终触发删除逻辑,因为您刚刚添加的框包含您要查找的文本。

我要么取消其他活动,要么您必须删除此行:

eq[eqNum].Text = "f = m * a";

【讨论】:

  • 谢谢,但字符串“f = m * a”与“f”、“m”或“a”不同。我不明白。请您进一步解释一下吗?
  • !((f && m) || (m && a) || (f && a)) && this.Controls.Contains(eq[eqNum]) -> ! (假 || 假 || 假) && 真 -> !(假) && 真 => 真 && 真。这意味着你总是会遇到其他问题。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-09
  • 2012-06-06
  • 2022-08-18
  • 2011-03-29
  • 2018-12-28
相关资源
最近更新 更多