0

I have 2 Forms In form 1 there is just a Button In form 2 there is just a web browser. I want to set the SMS Response stream in webbrowser.DocumentText

Cross-thread operation not valid: Control 'webBrowser1' accessed from a thread other than the thread it was created on.

    public partial class Form1 : Form
    {
        CookieContainer cookies = new CookieContainer();
        Form2 form2 = new Form2();
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {         
            Thread th = new Thread(Dowork);
            th.SetApartmentState(ApartmentState.STA);
            th.Start();
        }

        void Dowork()
        {
            try
            {
              Encoding charset = Encoding.GetEncoding("utf-8");
              HttpWebRequest SMSRequset = (HttpWebRequest)WebRequest.Create("http://www.iam.ma/_layouts/SharepointFreeSms/EnvoyerSms.aspx");
                SMSRequset.Method = "GET";
                SMSRequset.CookieContainer = cookies;
                HttpWebResponse SMSResponse = (HttpWebResponse)SMSRequset.GetResponse();
                System.IO.StreamReader reader2 = new System.IO.StreamReader(SMSResponse.GetResponseStream(), charset);

                form2.Show();
                form2.Invoke((MethodInvoker)delegate
                {
                    form2.webBrowser1.DocumentText = reader2.ReadToEnd();
                });
            }
            catch (Exception EX)

                {
                    MessageBox.Show(EX.Message);

                }
        }
}

What should I do ?

the error is here

form2.webBrowser1.DocumentText = reader2.ReadToEnd();
Dinesh Kanivu
  • 2,551
  • 1
  • 23
  • 55
Abdex
  • 1
  • 5
  • possible duplicate of [Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on](http://stackoverflow.com/questions/142003/cross-thread-operation-not-valid-control-accessed-from-a-thread-other-than-the) – John Saunders Jan 26 '14 at 12:57
  • When you're trying to troubleshoot, `ex.Message` isn't good enough. Use `ex.ToString()`. – John Saunders Jan 26 '14 at 13:00

1 Answers1

0

Change all your code to be executed via the invoke:

form2.Show();
   Encoding charset = Encoding.GetEncoding("utf-8");
   HttpWebRequest SMSRequset =  (HttpWebRequest)WebRequest.Create("http://www.iam.ma/_layouts/SharepointFreeSms/EnvoyerSms.aspx");  
   SMSRequset.Method = "GET";
   SMSRequset.CookieContainer = cookies;
   HttpWebResponse SMSResponse = (HttpWebResponse)SMSRequset.GetResponse();
   System.IO.StreamReader reader2 = new System.IO.StreamReader(SMSResponse.GetResponseStream(), charset);
form2.webBrowser1.Invoke((MethodInvoker)delegate
{
   form2.webBrowser1.DocumentText = reader2.ReadToEnd();
});
T McKeown
  • 12,971
  • 1
  • 25
  • 32