Gm Basha
Gm Basha

Reputation: 53

How to display messagebox only one time in a loop

I am New In C sharp,

I am using messagebox to display the line. but it is in a loop so the messagebox display more times i want to display it only one time and message box should not be display for the next time.

try{
    using (var sr = File.OpenText("test.txt")){
        string newone = 20110501;//date
        string line;
        while ((line = sr.ReadLine()) != null){
            if (three => one){
                MessageBox.Show("Buy : " + line);
                //Its Displaying more than 50 times i want to displayit only
                //onetime and should dispose for the next Time
            }
        }
    }
} catch { }

Thanks In Advance.

Upvotes: 0

Views: 10981

Answers (3)

amiry jd
amiry jd

Reputation: 27585

use this:

try {
    using (var sr = File.OpenText("test.txt")) {
        bool flag = true;
        string newone = 20110501;//date
        string line;
        while ((line = sr.ReadLine()) != null) {
            if (flag) {
                MessageBox.Show("Buy : " + line);
                //Its Displaying more than 50 times i want to displayit only
                //onetime and should dispose for the next Time
            }
            flag = false;
        }
    }
} catch { }

Upvotes: 5

SLaks
SLaks

Reputation: 887295

You're trying to break; from the loop.

Upvotes: 2

K-ballo
K-ballo

Reputation: 81349

Simple have a boolean flag saying whether the message box has already been shown or not, and use it to guard that action.

Update:

bool shown = false;
...
if( !shown )
{
     MessageBox.Show("Buy : " + line);
     shown = true;
}

Upvotes: 3

Related Questions