如何用While语句实现TextBox输入Easter Bunny后Label显示10次?
Fixing Your Easter Bunny Label Display Issue
Got it, let's break down why your current code isn't doing what you need, then fix it step by step to get that "Easter Bunny" text showing 10 times in label1 when you type the phrase.
What's Off with Your Existing Code?
- No input check: Right now, your code runs every time the text in
textBox1changes—regardless of whether you typed "Easter Bunny" or not. - Infinite loop risk: You set
p = paashaasonce at the start, but never updatepagain. Sincepaashaasincrements butpstays stuck at 0,p <=4is always true—this would keep popping up message boxes forever if you let it! - Wrong loop count:
p <=4only runs 5 times (0 to 4), not the 10 iterations you need. - Wrong output target: You're using
MessageBox.Show()instead of updating the text inlabel1.
Corrected Code
Here's the adjusted version that meets your exact requirement:
private void textBox1_TextChanged(object sender, EventArgs e) { // First, check if the input matches "Easter Bunny" (case-insensitive option included) if (textBox1.Text.Equals("Easter Bunny", StringComparison.OrdinalIgnoreCase)) { int loopCount = 0; // Clear the label first so we start with a fresh state label1.Text = string.Empty; // Run the loop exactly 10 times while (loopCount < 10) { // Append "Easter Bunny" to the label (add a new line for readability) label1.Text += "Easter Bunny" + Environment.NewLine; loopCount++; } } else { // Optional: Clear the label if the input isn't our target phrase label1.Text = string.Empty; } }
Key Improvements Explained
- Input validation: The
ifstatement ensures the code only runs when the text intextBox1is exactly "Easter Bunny". We usedOrdinalIgnoreCaseso it works even if you type lowercase or mixed case—remove that part if you want strict case matching. - Proper loop control: Using
loopCount < 10guarantees exactly 10 iterations, and we incrementloopCounteach time to exit the loop cleanly. - Label-focused output: Instead of pop-up boxes, we directly update
label1.Text. AddingEnvironment.NewLineputs each instance on a new line, but you can swap that for a space or nothing if you want all text on one line. - Clean state: We clear the label before starting the loop so old text doesn't stick around, and optionally clear it when the input isn't our target phrase.
Extra Efficiency Tip
If you want to avoid updating the label 10 times in a row (which is a tiny bit inefficient), you can build the full string first then assign it to the label:
string bunnyText = string.Join(Environment.NewLine, Enumerable.Repeat("Easter Bunny", 10)); label1.Text = bunnyText;
This creates all 10 lines in one go and sets the label text once—neater and faster.
内容的提问来源于stack exchange,提问作者ZiggyMan ZiggyMan
相关产品推荐
相关产品推荐

