I am trying to run the following code in a thread but I keep getting this error:

Cross-thread operation not valid

for both listboxes.

Heres the code I am using:


                    for (int i = 0; i < listBox4.Items.Count; i++)
                        listBox4.SetSelected(i, true);
                        listBox5.SetSelected(i, true);

                        string[] details = { listBox4.SelectedItem.ToString(), listBox5.SelectedItem.ToString() };

                        foreach (string element in details)

                            string postData = "";
                            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("");
                            request.ContentType = "application/x-www-form-urlencoded";
                            request.ContentLength = postData.Length;
                            request.Method = "POST";
                            request.KeepAlive = true;

                            Stream response = request.GetRequestStream();
                            byte[] postBytes = Encoding.ASCII.GetBytes(postData);
                            response.Write(postBytes, 0, postBytes.Length);





                catch (Exception ex)



(I removed my postData and the site I am requesting too to protect my code form leechers)

This is a common problem with multi-threading.
It is only possible to change the properties of Components and Controls from the UI thread.
To change them from another thread, you must Invoke a method that does the change for you.

However, for what you are doing I do not think that Invoke is what you need.
You do not need to SetSelected on a ListBox item to get its value (unless you are relying on the result of a SelectionChanged event to do something else).
You can just reference the item directly from the ListBox.Items collection.
E.g. string[] details = {listBox4.Items[i].ToString(), listBox5.Items[i].ToString()};

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.20 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.