1

I have a for loop that I want (for every item in a ListBox) to execute a method.

What happening now is the first item is being selected, the method is being executed, but then it doesn't select the second item, it just sits there.

Can you help?

This is how my for loop looks:

for(int i = 0; i < listBox8.Items.Count; i++) {
    listBox8.SetSelected(i, true);
    listBox8.SelectedIndex = 0;

    Thread t = new Thread(signinmobile);
    t.Start();
    CheckForIllegalCrossThreadCalls = false;
}

And here is my sub:

public void signinmobile()
{
    string yourString = listBox8.SelectedItem.ToString();
    string[] strArray = yourString.Split(':');

    System.Net.ServicePointManager.Expect100Continue = false;
    string postData = "authenticity_token=401538d41ace8f334c3d&username=" + strArray[0] + "&password=" + strArray[1] + "";
    CookieContainer tempCookies = new CookieContainer();
    UTF8Encoding encoding = new UTF8Encoding();
    byte[] byteData = encoding.GetBytes(postData);

    HttpWebRequest postReq = (HttpWebRequest)WebRequest.Create("https://mobile.twitter.com/session");
    postReq.Method = "POST";
    postReq.KeepAlive = true;
    postReq.CookieContainer = tempCookies;
    postReq.ContentType = "application/x-www-form-urlencoded";
    postReq.Referer = "https://mobile.twitter.com/session";
    postReq.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; ru; rv:1.9.2.3) Gecko/20100401 Firefox/4.0 (.NET CLR 3.5.30729)";
    postReq.ContentLength = byteData.Length;

    Stream postreqstream = postReq.GetRequestStream();
    postreqstream.Write(byteData, 0, byteData.Length);
    postreqstream.Close();
    HttpWebResponse postresponse = default(HttpWebResponse);

    postresponse = (HttpWebResponse)postReq.GetResponse();
    tempCookies.Add(postresponse.Cookies);
    StreamReader postreqreader = new StreamReader(postresponse.GetResponseStream());

    string accountstatus = postreqreader.ReadToEnd();

    webBrowser1.DocumentText = accountstatus;

    if (accountstatus.Contains("Sign in information is not correct"))
    {
        listBox9.Items.Add(listBox8.SelectedItem.ToString() + "\r");
        while (listBox8.SelectedItems.Count > 0)
        {
            listBox8.Items.Remove(listBox8.SelectedItems[0]);
        }
    }
    else
    {
        listBox2.Items.Add(listBox8.SelectedItem.ToString() + "\r");

        while (listBox8.SelectedItems.Count > 0)
        {
            listBox8.Items.Remove(listBox8.SelectedItems[0]);
        }
    }
}
8
  • Why listBox8.SetSelected(i, true); then listBox8.SelectedIndex = 0;? I mean is there something else happening in there? Commented Nov 26, 2011 at 22:17
  • Are you using the list selection in the method signinmobile? if yes then can you please post that code? It does not look thread safe to me Commented Nov 26, 2011 at 22:21
  • @rfmodulator I just put both those lines to make sure it selects the first item because without them my for loop just stood idle not doing anything. And once the method is completed it removes the selecteditem. Commented Nov 26, 2011 at 22:22
  • @GETah I edited it and added the sub code Commented Nov 26, 2011 at 22:23
  • 1
    @GETah, of course it's not thread safe, he had to disable CheckForIllegalCrossThreadCalls for it to run in the first place. :) Commented Nov 26, 2011 at 22:27

4 Answers 4

1

Following line always selecting the first item for each loop cycle

listBox8.SelectedIndex = 0;

I believe you can remove this line at all because previous one (listBox8.SetSelected(i, true);) already does selection

EDIT: Since question was updated

I feel that here is exception may occur. Add try/catch(Exception ex) block around signinmobile method call and say us whether eny exception was handled.

BTW, Why you are running method in an other thread? Looks like there is thread sync issue so if list contains more then two items multiple threads would run and removing items in list, and then call to SetSelected fails since it cached index value i which currently not exists since some thread already removed item... So run all in single thread or do t.Join() after t.Start() so main thread would wait until working thread is done and them continue next loop cycle.

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

15 Comments

I forgot to say that the sub removes the selecteditem after its been called.
How you are removing the item from the list box? SHow please code
I feel that here is exception may occur, because you are removing Item inside a foreach loop. add try/catch(Exception ex) block around signinmobile method call and say us whether eny exception was handled
Hey, the first exception thrown was 'Index out of bounds of array', then 'Object reference not Set to the instance of an object' all referring to the listbox(es) no doubt
I am using a for loop not a foreach loop ._.
|
1

You set the selected index again to 0. That is the first item. So every iteration of the loop it stays at the first item.

1 Comment

I forgot to say that the sub removes the selecteditem after its been called.
1

You're resetting SelectedIndex to 0 each time, so it follows that it won't move forward... just remove that line.

1 Comment

I forgot to say that the sub removes the selecteditem after its been called.
0

The above answers have well caught the listBox8.SelectedIndex = 0; issue.

I just want to comment on the signinmobile method.

Gurus, correct me if I am wrong but if this method is using the list box selection to do some background work in the created thread then the whole thing won't work! By the time the created thread spins and starts working on the selected item string yourString = listBox8.SelectedItem.ToString(); the parent thread will change the selection in the for loop listBox8.SetSelected(i, true); which might disturb the previously created worker thread. To make sure this is thread safe, I would extract the item to work on on the for loop and pass it as a string to the worker thread. This way you are 100% sure only one thread accesses the list box and changes its selection.

Suggested fix

for(int i = 0; i < listBox8.Items.Count; i++) {
    Thread t = new Thread(new ParameterizedThreadStart(signinmobile));
    t.Start(listBox8.Items[i].ToString());
}
// Now that you started all thread to work on all items
// You can cleanup the list box safely

public void signinmobile(string parameter) {
    string yourString = parameter; // No need to access the shared list
    //...
    if (accountstatus.Contains("Sign in information is not correct")) {
       listBox9.Items.Add(parameter + "\r");
       // No need to access the shared list to remove the item
    } else  {
       listBox2.Items.Add(parameter + "\r");
       // No need to access the shared list to remove the item
    }
}

3 Comments

Im working with a for loop not a foreach or should I switch to a foreach?
@user1017524 Just edited my code to work with a for loop instead. Hope this helps
Nope I still need help with the issue. Thanks but I think your answer might be a too complex for what I am doing :/

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.