c# – Print List<Message> in ListBox

Question:

Hi. I want to display List with email in ListBox

public void FetchAllMessages()
        {
            using (Pop3Client client = new Pop3Client())
            {
                client.Connect("pop.gmail.com", 995, true);
                client.Authenticate(mail, pass);
                messageCount = client.GetMessageCount();
                allMessages = new List<Message>(messageCount);
                for (int i = 0; i > messageCount - 1; i++)
                {
                    allMessages.Add(client.GetMessage(i));
                    list.Items.Add(allMessages[i]);
                }

            }
        }

This function is executed when the button is clicked but the ListBox is not filled. What I am doing wrong.

Answer:

Perhaps the problem is that you are blocking the UI thread. Try to separate reading from UI operations.

In addition, you have an error in the loop condition: the i > messageCount - 1 condition i > messageCount - 1 most likely never met.

Then what is your Pop3Client ? There is no such standard class. If it is OpenPop.NET Pop3Client , its messages are numbered for some reason from one .

With this in mind, we get the following code:

public List<Message> FetchAllMessages()
{
    using (Pop3Client client = new Pop3Client())
    {
        client.Connect("pop.gmail.com", 995, true);
        client.Authenticate(mail, pass);
        var messageCount = client.GetMessageCount();
        var messages = new List<Message>(messageCount);
        for (int i = 0; i < messageCount; i++)
            messages.Add(client.GetMessage(i + 1));
        return messages;
    }
}
allMessages = await Task.Run(() => FetchAllMessages());
messageCount = allMessages.Count;
foreach (var message in allMessages)
    list.Items.Add(message);

Yes, and for ListBox you need to define an appropriate ItemTemplate .

Scroll to Top