1

I have ListBox called lstProductGroups.

On a simple Windows Form, a method called GetGroups gives me string groups selected by the user like Cars, Bikes etc.

public List<string> GetGroups()
{
    List<string> prodGroups = (from object item in lstProductGroups.SelectedItems select item.ToString()).ToList();

    return prodGroups;
}

But if I try to access same method from another thread I get all items in my list called System.Data.DataRowView.

I even tried it in a foreach loop with BeginInvoke, but the item.ToString() always returns System.Data.DataRowView.

I am new to Winforms with threading. What am I doing wrong?

4
  • What are you using to facilitate threading; BackgroundWorker, Thread, Task? Commented Mar 27, 2012 at 10:29
  • Did you try to call GetGroups() method from the other thread with Invoke()? It should return the right list. Commented Mar 27, 2012 at 10:33
  • Third party API's event that I am subscribed to. I do not know their internal implementation. But any UI update code from the event method raised Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on. Commented Mar 27, 2012 at 10:34
  • @Adriano tried it. Still same thing. Commented Mar 27, 2012 at 10:41

2 Answers 2

1

First declare a delegate:

delegate List<string> GetItemsDlg();

Change your method like this:

List<string> GetGroups() {
    if (lstProductGroups.InvokeRequired) {
        var dlg = new GetItemsDlg(GetGroups);
        return lstProductGroups.Invoke(dlg) as List<string>;
    }
    List<string> prodGroups = (from object item in lstProductGroups.SelectedItems select item.ToString()).ToList();

    return prodGroups;

}

Call your method:

List<string> items = GetGroups();
Sign up to request clarification or add additional context in comments.

Comments

0

How about invoke:

Invoke((MethodInvoker) delegate
                               {
                                 ...
                               }

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.