-1
string path = "xx\\xx.txt";
string[] memo = System.IO.File.ReadAllLines(path);
int totalLines = textBox2.Lines.Length;
string lastLine = textBox2.Lines[totalLines - 1];
for (int i = 0; i < 5; i++)
{
    string a = memo[i];          
    if (a.Contains(lastLine))
    {             
        textBox2.Text = (textBox2.Text + Environment.NewLine + memo[i + 1]);
                           
     }                  
}

Check the notepad from lines 0 to 4

if (a.Contains(lastLine))
{
    textBox2.Text = (textBox2.Text + Environment.NewLine + memo[i + 1]);

}

I want to make above code run only once. However, because there is a memo[i+1] variable i. Under the influence of the for statement that repeats 5 times, the text 5 times is input.

How can I fix it?

Sunil
  • 3,404
  • 10
  • 23
  • 31
mr.G
  • 109
  • 1
  • 7
  • Use the [break](https://learn.microsoft.com/dotnet/csharp/language-reference/keywords/break) instruction in the test block just after the assignment. I hope this can help you to enjoy C# coding: [How do I improve my knowledge in C#](http://www.ordisoftware.com/files/stack-overflow/CsharpBegin.htm) –  Dec 12 '20 at 17:57
  • 1
    Does this answer your question? [C# loop - break vs. continue](https://stackoverflow.com/questions/6414/c-sharp-loop-break-vs-continue) –  Dec 12 '20 at 17:58
  • 2
    if you need to stop your loop when something is found, you are using the wrong loop. You should use a conditional loop like `while` not an unconditional loop – GuidoG Dec 12 '20 at 21:22

1 Answers1

3

Simply add a break statement

if (a.Contains(lastLine))
{
    textBox2.Text = (textBox2.Text + Environment.NewLine + memo[i + 1]);
    break;
}
Sunil
  • 3,404
  • 10
  • 23
  • 31
  • I do this again actually, the code problem is under the code if (e.KeyChar == (char)13) { } when I used key press event question code do not work but If I used button event the question code actually work – mr.G Dec 13 '20 at 02:52
  • I found the issue – mr.G Dec 13 '20 at 02:54