0

I have a frustrating problem. With the following code in my clsExchange which is called in my FormExchange with simply txtPhonesInSystem.Text = ClsExchange.listPhones();I can only display the first arraylist entry.

 public string listPhones()
    {
        string strphone = string.Empty;

        foreach (clsPhone phone in phoneArray)
        {

            strphone = (strphone + phone.PhoneNumber.ToString() + "\n");
            return strphone;


        }
        return strphone;
    }

However, if i take the logic and put in in the btn_press event on the form.cs it displays the complete contents. The only difference I can see is instead of return strphone I use txtbox.Text=strphone. Any suggestions greatly appreciated aS I have been at this all day.

EDIT Thankyou all for your answers. I new it had to be something as simple as that. I guess my brain isn't made right for this stuff. Shame because I love it.

4
  • 2
    You don't need the return strphone line in your foreach Commented Nov 30, 2011 at 17:26
  • You can also write the concat line more succintly: strphone += String.Format("{0}{1}", phone.PhoneNumber, Environment.NewLine); Commented Nov 30, 2011 at 17:26
  • Ah, I get what you mean, sorry. You can also then do (in the form load or similar) txtbox.Text = listPhones(); Commented Nov 30, 2011 at 17:28
  • 1
    The "only difference" you can see is the is cause of the problem. C# return keyword. Commented Nov 30, 2011 at 17:29

2 Answers 2

2

This line inside the foreach is the problem:

return strphone;

You're quitting on the first record.

As an aside, is this still C# 1.0? If not, why are you using ArrayLists?

Sign up to request clarification or add additional context in comments.

1 Comment

No, but doing it this simple way to get it working then planning on converting to hashtable so i can remove entries without upsetting the index.
1

You are calling return in the foreach loop which force to exit entire method at the first loop cycle so strphone contains only the first phome number.

If you are usign .NET 3 you can simplify solution using single LINQ query:

txtPhonesInSystem.Text = 
          phoneArray.Select(p => p.PhoneNumber)
                    .Aggregate((acc, next) => acc + "\n" + next);

otherwise just remove return strphone; line of code.

Also it makes sense using Environment.NewLine instead of hard coded "\n" value.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.