Results 1 to 3 of 3

Thread: Thread error when using BackcroundWork w/ Excel

  1. #1

    Thread Starter
    Hyperactive Member
    Join Date
    Nov 2005
    Posts
    310

    Thread error when using BackcroundWork w/ Excel

    I am trying to export my ListView items to excel file
    But when I tried to use backgroundworker to do the job without freezing my UI Window.
    And error occurred when the process start to loop through the items.
    Here is my code under bagcroundworker do_work event
    cross thread error event at this point of code foreach (ListViewItem.ListViewSubItem lvs in lvi.SubItems)
    I wonder why there is no cross thread error on my first loop.
    Code:
    {
                Excel.Application app = new Excel.Application();
                app.Visible = true;
                Workbook wb = app.Workbooks.Add(1);
                Worksheet ws = (Worksheet)wb.Worksheets.get_Item(1);
                Excel.Range rng;
                rng = ws.get_Range("A9", "F9");
                ws.get_Range("C3", "E3").Merge();
                ws.get_Range("C4", "D4").Merge();
                ws.get_Range("C5", "E5").Merge();
                ws.Cells[3, 3] = "----------";
                ws.Cells[4, 3] = "REPORT OF: ";
                ws.Cells[5, 3] = "AS OF: " + DateTime.Today.Year.ToString();
                ws.get_Range("B3", "F3").Font.Bold = true;
                ws.get_Range("B3", "F3").Font.Size = 14;
                rng.Interior.Color = Color.FromName("Teal");
                rng.Font.Bold = true;
                ws.Cells[lvResult.Items.Count + 12, 6] = "TOTAL: " + lvResult.Items.Count.ToString();
                ws.Shapes.AddPicture(System.Windows.Forms.Application.StartupPath + "\\assets\\logo.png", MsoTriState.msoFalse, MsoTriState.msoTrue, 5, 10, 100, 100);
    
                int i = 1;
                int j = 11;
                try
                {
                    int k = 1;
                    foreach (ColumnHeader col in lvResult.Columns)
                    {
                        ws.Cells[9, k++] = col.Text;
                    }
    
                    foreach (ListViewItem lvi in lvResult.Items)
                    {
                        i = 1;
                        foreach (ListViewItem.ListViewSubItem lvs in lvi.SubItems)
                        {
                            Excel.Range r = (Excel.Range)ws.Cells[j, i];
                            r.Value = lvs.Text;
                            bgExport.ReportProgress(i / 100);
                            i++;
    
                        }
                        j++;
                    }
                    ws.Columns.AutoFit();
                }
    
                catch (Exception ex)
                {
                    MessageBox.Show("Error encountered while exporting.\r\nExport will exit.\r\n" + ex.ToString(), "Warning");
                }
    Last edited by dr_aybyd; Feb 24th, 2013 at 07:50 PM.
    VB 6.0 = "Self-Study" Then
    vb.NET = "Self-Study" Then
    C# = 'on going study.....

  2. #2
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,222

    Re: Thread error when using BackcroundWork w/ Excel

    A BackgroundWorker is, as the name suggests, for doing background work. Anything to do with the UI is inherently foreground work, the opposite of background work. You make reference to your ListView in that code, so that is interacting with the UI so that is foreground work. If you need to use data obtained from the UI in your DoWork event handler then you need to pass it in via the RunWorkerAsync method. In your case, getting the Text of each item and subitem is still interacting with the UI so you have two options:

    1. Extract all the data from the ListView on the UI thread first and pass it in as an array or whatever when calling RunWorkerAsync.
    2. Pass in just the item count and then use a loop to call ReportProgress and get the data one item at a time in the ProgressChanged event handler.

    With regards to option 2, many people forget the fact that the 'userState' parameter of the ReportProgress method is type Object, so it can be used to pass data from the ProgressChanged event handler back to the DoWork event handler is desired. For instance, if you pass an object with a String property as an argument, you can set that String property in the ProgressChanged event handler and then get it back in the DoWork event handler.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  3. #3

    Thread Starter
    Hyperactive Member
    Join Date
    Nov 2005
    Posts
    310

    Re: Thread error when using BackcroundWork w/ Excel

    Ok I'll recode my codes according to your suggestions.
    I'll keep update this thread.


    tnx jm
    VB 6.0 = "Self-Study" Then
    vb.NET = "Self-Study" Then
    C# = 'on going study.....

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width