You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现TextBox含指定短语时仅执行一次对应操作?

Fixing Repeated Operation Execution When Phrase Appears Multiple Times in TextBox

Got it, let's tackle this problem where your debug message keeps popping up multiple times every time "hello world" shows up more than once in the TextBox. Here are two straightforward solutions to make sure the action runs only once:

Solution 1: Use a Boolean Flag (Flexible for Reset Scenarios)

The easiest way is to add a flag variable to track whether we've already executed the action. This works great if you might need to reset the behavior later (like if the user deletes the phrase and retypes it).

First, declare a private boolean variable in your class:

private bool _hasExecutedAction = false;

Then update your check logic (probably in the TextChanged event handler or wherever you're running the check):

private void TextBox1_TextChanged(object sender, EventArgs e)
{
    // Only run if we haven't executed the action yet AND the phrase exists
    if (!_hasExecutedAction && textbox1.Text.Contains("hello world"))
    {
        System.Diagnostics.Debug.WriteLine("Hi");
        _hasExecutedAction = true; // Mark the action as done
    }
}

Bonus: Resetting the Flag

If you want to allow the action to run again (e.g., when the user clears the TextBox), add a check to reset the flag:

// Add this inside the same event handler or another appropriate place
if (string.IsNullOrEmpty(textbox1.Text))
{
    _hasExecutedAction = false;
}

Solution 2: Remove the Event Handler (One-Time Only Scenario)

If you never need to run the action again after the first time, you can simply remove the event handler once the action is executed. This stops the check from running entirely on future text changes.

private void TextBox1_TextChanged(object sender, EventArgs e)
{
    if (textbox1.Text.Contains("hello world"))
    {
        System.Diagnostics.Debug.WriteLine("Hi");
        // Unsubscribe from the event so this logic never runs again
        textbox1.TextChanged -= TextBox1_TextChanged;
    }
}

Note

This method is permanent for the current instance of the TextBox—you won't get any more updates from the TextChanged event unless you re-subscribe to it later. Pick this only if you don't need to monitor the TextBox's text after the first match.


内容的提问来源于stack exchange,提问作者Devansh Tayal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:01:17