如何实现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

