engineer41
engineer41

Reputation: 81

unable to show the last item in the stack pop ()

I'm implementing backword function on a button. that when clicked moves to the previous link in the stack. the problem is this if it has one element in the stack pop() it gives an error of stack empty.

 private void Backward_Click(object sender, EventArgs e)
{
try
{
if (simpleStack.Count != 0)
{
simpleStack.Pop();
string open = simpleStack.Pop();

PopulateListView(open);

complicatedStack.Push(open);

}

else if (simpleStack.Count == 0)
{
Backward.Enabled = false;

}

It works when I have more than one clicks n goes back to the previous item selected.but does not show the last one. I'm passing string in simpleStack. can anybody tell me what I'm missing?

Upvotes: 0

Views: 807

Answers (2)

Prateek Singh
Prateek Singh

Reputation: 863

Try this -

private void Backward_Click(object sender, EventArgs e)
    {
        try
        {
            if (simpleStack.Count != 0)
            {
                //simpleStack.Pop();    // Remove this line
                string open = simpleStack.Pop();

                PopulateListView(open);

                complicatedStack.Push(open);

            }
            else if (simpleStack.Count == 0)
            {
                Backward.Enabled = false;
            }
        }
    }

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500893

Look at your code:

simpleStack.Pop();
string open = simpleStack.Pop();

You're popping twice, and ignoring the first result. Why would you do that? I suspect you can just remove the first Pop call.

Also note that your else clause doesn't need to check simpleStack.Count == 0 - it must be, otherwise you wouldn't be evaluating the else clause. (Unless you've got multiple threads doing stuff of course - which wouldn't be a good idea.)

Upvotes: 4

Related Questions