Hello I am working with my web browser and I keep getting the following error: Cannot access a disposed object.
Object name: ‘WebBrowser’.
What I am trying to do with my code is loop through every item in a listbox, visit a page, make a message box saying success popup, then move down to the next item. What happens is it only says ‘Success’ for the first two items then it stops working for the third and when I close down my program I get the error/warning listed above.
This is my code:
listBox3.SelectedIndex = 0;
for (int i = 0; i < listBox3.Items.Count; i++)
{
completed();
move();
}
This is the code for the completed():
webBrowser1.Navigate(listBox3.SelectedItem.ToString());
while (!(webBrowser1.ReadyState == WebBrowserReadyState.Complete))
{
Application.DoEvents();
if (webBrowser1.ReadyState == WebBrowserReadyState.Complete)
{
MessageBox.Show("Success!");
}
}
This is the code for the move():
listBox3.SelectedIndex = +1;
webBrowser1.Navigate(listBox3.SelectedItem.ToString());
while (!(webBrowser1.ReadyState == WebBrowserReadyState.Complete))
{
Application.DoEvents();
if (webBrowser1.ReadyState == WebBrowserReadyState.Complete)
{
MessageBox.Show("Success!");
}
}
And I get the error in this line:
if (webBrowser1.ReadyState == WebBrowserReadyState.Complete)
{
....
You attempt to access
webBrowser1, but it’s been disposed of since it’s no longer needed by the form. You can protect against this by checking forwebBrowser1.IsDisposedand exiting the loop if it is, afterApplication.DoEvents(), like so:Also, I can’t say for certain since I don’t have the entire code, but… a loop is very inefficient there. It will hog CPU cycles doing nothing. A better solution might be to handle the
WebBrowser‘sDocumentCompletedevent.