How to change ListView inside background worker? Through Thread Error

Possible duplicate:
The shortest and most correct way to avoid cross-flow errors?

I had an error starting my programs .... {"Cross-stream operation incorrect: the" listView1 "control is accessible from a stream other than the stream in which it was created." }

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { TestObject argumentTest = e.Argument as TestObject; string[] lines = argumentTest.ThreeValue.Split(new string[] { Environment.NewLine }, StringSplitOptions.None); HtmlAgilityPack.HtmlDocument document = new HtmlAgilityPack.HtmlDocument(); foreach (string vr in lines) { string country = argumentTest.OneValue.Trim(); string url = vr + country + '/code/' + argumentTest.TwoValue.Trim(); string sourceCode = WorkerClass.getSourceCode(url); document.LoadHtml(sourceCode); var title = document.DocumentNode.SelectSingleNode("//title"); var desc = document.DocumentNode.SelectSingleNode("//div[@class='productDescription']"); //-- eksekusi title string isititle = title.InnerText; string isititle2 = isititle.Replace("droidflashgame: ", ""); string isititle3 = Regex.Replace(isititle2, "[^A-Za-z0-9 ]+", ""); string isititle4 = isititle3.Substring(0, Math.Min(isititle3.Length, 120)); //-- Adding to list view for next step... ListViewItem abg = new ListViewItem(isititle3); abg.SubItems.Add(isititle4); listView1.Items.Add(abg); // ERROR in Here? 

In some tutorial, did I know that using invoke? but I tried a lot of things, but still a mistake?

Any hand?

+4
source share
3 answers

Try it. This works great for me.

  ListViewItem abg = new ListViewItem(isititle3); if (listView1.InvokeRequired) listView1.Invoke(new MethodInvoker(delegate { listView1.Items.Add(abg); })); else listView1.Items.Add(abg); 
+9
source

Remove the last line (listView1.Items.Add (abg); // ERROR here?) From your code and replace it with this:

 AddListViewItem(abg); 

Then this method for your code:

  delegate void AddListViewItemDelegate(ListViewItem abg); void AddListViewItem(ListViewItem abg) { if (this.InvokeRequired) { AddListViewItemDelegate del = new AddListViewItemDelegate(AddListViewItem); this.Invoke(del, new object() { abg }); } else { listView1.Items.Add(abg); } } 

It will do the job, happy walking!

+2
source

When you use a background worker, you can simply pass the element through a modified move:

 private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { //.......... var test = new ListViewItem("test"); backgroundWorker1.ReportProgress(0, test); } private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e) { listView1.Items.Add((ListViewItem)e.UserState); } 
0
source

All Articles