locked
Error: Invoke or BeginInvoke cannot be called on a control until the window handle has been created RRS feed

  • Question


  • When I open report by click button event - on the first time it opens, but on the second time (when I close report and open again), app breaks and appears error message:

    System.InvalidOperationException was unhandled
      Message="Invoke or BeginInvoke cannot be called on a control until the window handle has been created."
      Source="System.Windows.Forms"
      StackTrace:
           at System.Windows.Forms.Control.MarshaledInvoke(Control caller, Delegate method, Object[] args, Boolean synchronous)
           at System.Windows.Forms.Control.BeginInvoke(Delegate method, Object[] args)
           at Microsoft.Reporting.WinForms.ReportViewer.OnRenderingComplete(ProcessThreadResult result, PostRenderArgs data)
           at Microsoft.Reporting.WinForms.ProcessThreadArg.OnComplete(ProcessThreadResult result)
           at Microsoft.Reporting.WinForms.ProcessingThread.ProcessThreadMain(Object arg)
           at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
           at System.Threading.ExecutionContext.runTryCode(Object userData)
           at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
           at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
           at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
           at System.Threading.ThreadHelper.ThreadStart(Object obj)


    I was not use threads and I cannot locate cause of error.
    Thank you for any help.



    Saturday, April 5, 2008 7:42 PM

Answers

  • With this update, it would probably be InitializeReport that I pushed into "load"... fortunately this is even easier - you can do it from the caller - instead of calling InitializeReport directly, defer it to the Load event:

     

    Code Snippet

    f.Load += delegate

    {

      f.InitializeReport("Reports", "Bill", reportSourceFile, new ReportDataSource("Cash_Cash", ds.Tables[0]));

    };

    f.Show();

     

     

     

    Saturday, April 5, 2008 10:44 PM

All replies

  • Well, you haven't given us much clue what you might be doing.... but essentially that means that something is calling Invoke/BeginInvoke too early - in particular, you can get this if calling Invoke / BeginInvoke in the constructor. Can you give some clues what your code is doing immediately before this fails?
    Saturday, April 5, 2008 8:39 PM
  • Please post your code that is causing this error.

     

    Saturday, April 5, 2008 8:59 PM
  • Thank you for answering. The main part report's code:

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Data.SqlClient;
    using System.Drawing;
    using System.Text;
    using System.Windows.Forms;
    using Microsoft.Reporting.WinForms;
    using System.IO;
    using System.Collections;
    using System.Configuration;
    using System.Management;
    namespace DatabaseAccessWithADONET
    {
        public partial class ReportViewerFormIzv : Form
        {
            private static string ConStr = ConfigurationManager.ConnectionStrings["DatabaseAccessWithADONET.Properties.Settings.PersonDatabaseConnectionString"].ConnectionString;

            BindingManagerBase bindManager;
            private bool PrintLayout = true;
            bool loaded = false;
            private CustomReportViewerMessages customMessages = null;
            int current,max,tip;
            public ReportViewerFormIzv()
            {              
                    InitializeComponent();
                    customizeReportViewer();
                    this.bindManager = this.BindingContext[this.cash.vReportBill, "IDBill"];
                    current = 0; tip = 0;
            }   

            private void customizeReportViewer()
            {
               
                    ToolStrip toolStrip = this.ToolStrip;

                    if (toolStrip != null)
                    {
                        toolStrip.ImageList = this.reportViewerImageList;

                        toolStrip.Items["find"].ImageKey = "btnFind.Image";
                        toolStrip.Items["findNext"].ImageKey = "btnFindNext.Image";

                        int zoomPos = toolStrip.Items.IndexOfKey("zoom");
                        if (zoomPos >= 0)
                        {
                            toolStrip.Items.Insert(zoomPos + 1, this.addDefaultSeparator("additionalSeparator1"));
                            toolStrip.Items.Insert(zoomPos + 1, this.addDefaultLabel("lblSeparator", String.Empty, 100));
                            toolStrip.Items.Insert(zoomPos + 1, this.addDefaultSeparator("additionalSeparator2"));
                            toolStrip.Items.Insert(zoomPos + 1, this.addDefaultButton("btnClose", "Close", "btnClose.Image", new EventHandler(ButtonClose)));
                            toolStrip.Items.Insert(zoomPos + 1, this.addDefaultButton("btnHelp", "Help", "btnHelp.Image", null));
                            toolStrip.Items.Insert(zoomPos + 1, this.addDefaultSeparator("additionalSeparator3"));
                        }

                         toolStrip.Items[16].Click += new EventHandler(ReportViewerForm_Click);
                        toolStrip.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));

                        foreach (ToolStripItem t in toolStrip.Items)
                        {
                            t.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                        }
                        ToolStripDropDownButton exportButton = toolStrip.Items["export"] as ToolStripDropDownButton;
                        if (exportButton != null)
                            exportButton.DropDownOpened += new EventHandler(this.OnExportOpened);
                    }
            }

           
            private ToolStripButton addDefaultButton(string name, string text, string imageResource, EventHandler eventHandler)
            {
               
                    ToolStripButton result = new ToolStripButton();

                    result.Name = name;
                    result.Size = new System.Drawing.Size(23, 22);
                    result.Text = text;

                    if (imageResource == String.Empty)
                        result.DisplayStyle = ToolStripItemDisplayStyle.Text;
                    else
                    {
                        result.DisplayStyle = ToolStripItemDisplayStyle.Image;
                        result.ImageKey = imageResource;
                    }

                    if (eventHandler != null)
                        result.Click += eventHandler;

                    return result;
              
            }

            private ToolStripLabel addDefaultLabel(string name, string text)
            {    
                   return addDefaultLabel(name, text, 0);
            }

            private ToolStripLabel addDefaultLabel(string name, string text, int width)
            {
                    ToolStripLabel result = new ToolStripLabel();

                    result.Name = name;
                    result.Text = text;

                    result.AutoSize = (width <= 0);

                    if (!result.AutoSize)
                        result.Size = new System.Drawing.Size(width, 22);

                    return result;     
            }

            private ToolStripSeparator addDefaultSeparator(string name)
            {       
                    ToolStripSeparator result = new ToolStripSeparator();
                    result.Name = name;
                    result.Size = new System.Drawing.Size(6, 25);
                    return result;        
            }

            private TClass FindToolStrip<TClass>(Control control)
                where TClass : System.Windows.Forms.Control
            {
               
                    if (control == null)
                        return default(TClass);
                    else if (control is TClass)
                        return (TClass)control;
                    else
                    {
                        TClass result = default(TClass);
                        foreach (Control embedded in control.Controls)
                        {
                            if (result == null)
                                result = FindToolStrip<TClass>(embedded);
                        }

                        return result;
                    }          
            }


            public void InitializeReport(string formName, string reportDisplayName, string reportPath, ReportDataSource reportDataSource)
            {
                    this.Text = formName;
                    this.reportViewer.Reset();
                    this.reportViewer.LocalReport.DisplayName = reportDisplayName;
                    this.reportViewer.DocumentMapCollapsed = true;
                    this.reportViewer.LocalReport.ReportPath = reportPath;
                    this.reportViewer.Messages = this.customMessages;
                    this.reportViewer.LocalReport.DataSources.Add(reportDataSource);
                    this.reportViewer.RefreshReport();
              
            }
                
           
            private ToolStrip ToolStrip
            {
                get { return this.FindToolStrip<ToolStrip>(this.reportViewer ); }
            }


            private void reportViewer_RenderingComplete(object sender, RenderingCompleteEventArgs e)
            {
              
                    if (!loaded)
                    {
                        this.reportViewer.SetDisplayMode(Microsoft.Reporting.WinForms.DisplayMode.PrintLayout);
                        this.reportViewer.ZoomMode = Microsoft.Reporting.WinForms.ZoomMode.FullPage;
                        loaded = true;
                    }
                    switch (tip)
                    {
                        case 0:
                            this.reportViewer.LocalReport.DisplayName = "Cash bill "+ cmbBon.Text;
                            break;
                        case 1:
                            this.reportViewer.LocalReport.DisplayName = "Cheque bill " + cmbBon.Text;
                            break;
                        case 2:
                            this.reportViewer.LocalReport.DisplayName = "Sell Products " + cmbDate.Text.Replace(':','.');
                            break;
                        default: break;
                    }       
            }

            private void ReportViewerForm_Load(object sender, EventArgs e)
            {
                 using (SqlConnection veza = new SqlConnection(ConStr))
                {
                    veza.Open();
                    SqlDataAdapter da = new SqlDataAdapter("Select * from vReportProduct order by Date desc", veza);
                    da.Fill(this.cash.vReportProduct);
                    vReportProductBindingSource.Sort = "Date DESC";

                }

                this.ReportProductTableAdapter.Fill(this.cash.ReportProduct);
              
                    cash.ReportBill.AcceptChanges();
                   
                    using (SqlConnection veza = new SqlConnection(ConStr))
                    {
                        SemiQuery sq = new SemiQuery();
                        veza.Open();
                        SqlDataAdapter da = new SqlDataAdapter("Select * from vReportBill where Tip=0 order by Date desc", veza);
                        cash.vReportBill.Clear();
                        da.Fill(this.cash.vReportBill);
                        max = cash.vReportBill.Rows.Count;
                        tip = 0;
                        DataSet ds = new DataSet();
                        string reportSourceFile = sq.getProjectSourcePath() + @"\ReportGot.rdlc";
                        SqlDataAdapter dak;
                        if (cash.vReportBill.Rows.Count > 0)
                        {
                            dak = new SqlDataAdapter("SELECT * FROM ReportBill where IDBill=" + cash.vReportBill.Rows[current]["IDBill"].ToString() + " order by Date desc", veza);

                        }
                        else
                        {
                            dak = new SqlDataAdapter("SELECT * FROM ReportBill where IDBill=0", veza);
                        }
                        dak.Fill(ds);
                        InitializeReport("Reports", "Cash Bill", reportSourceFile, new ReportDataSource("Cash_Cash", ds.Tables[0]));

                        this.bindingNavigator1.BindingSource = this.vReportBillBindingSource;
                        cmbBon.Visible = true;
                        lblBon.Visible = true;
                        cmbDate.DataSource = vReportBillBindingSource;
                        cmbDate.ValueMember = "IDBill";
                        cmbDate.DisplayMember = "Date";
                        this.cmbDate.FormatString = "g";

                    }

                    outlookBar1.SelectedButton = outlookBar1.Buttons[0];
                    panel1.Visible = true;

                    loaded = true;
                    this.reportViewer.RenderingComplete += new Microsoft.Reporting.WinForms.RenderingCompleteEventHandler(this.reportViewer_RenderingComplete);

                    this.reportViewer.SetDisplayMode(Microsoft.Reporting.WinForms.DisplayMode.PrintLayout);
                    this.reportViewer.ZoomMode = Microsoft.Reporting.WinForms.ZoomMode.FullPage;
                    this.WindowState = FormWindowState.Maximized;
                    max = cash.vReportBill.Count;     
            }   
        }
    }
    Saturday, April 5, 2008 9:22 PM
  • Well, the first thing I'd try is moving the three lines into OnLoad instead of the constructor; at this point the handle may be available... worth a try...

    Code Snippet

     

    protected override void OnLoad(EventArgs e)

    {

        base.OnLoad(e);

        customizeReportViewer();

        this.bindManager = this.BindingContext[this.cash.vReportBill, "IDBill"];

        current = 0; tip = 0;

    }

     

     

    Saturday, April 5, 2008 9:30 PM
  •  milicica wrote:
    When I open report by click button event

     

    Can you post that method?

    Saturday, April 5, 2008 9:32 PM

  • private void btnReport_Click(object sender, EventArgs e)
             {
                    string reportSourceFile = getProjectSourcePath() + @"\ReportGot.rdlc";
                    ReportViewerFormIzv f = new ReportViewerFormIzv();
                  
                    SqlConnection mConnection = new SqlConnection(ConStr);                 
                    SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM ReportBill", mConnection);
                    DataSet ds = new DataSet();                 
                    da.Fill(ds);
                    f.InitializeReport("Reports", "Bill", reportSourceFile, new ReportDataSource("Cash_Cash", ds.Tables[0]));
                    f.Show();
                 }

    And I nowhere use any Invoke() or BeginInvoke(). Whole code is pretty long for placing here. Thank you again.

    Saturday, April 5, 2008 10:08 PM
  • With this update, it would probably be InitializeReport that I pushed into "load"... fortunately this is even easier - you can do it from the caller - instead of calling InitializeReport directly, defer it to the Load event:

     

    Code Snippet

    f.Load += delegate

    {

      f.InitializeReport("Reports", "Bill", reportSourceFile, new ReportDataSource("Cash_Cash", ds.Tables[0]));

    };

    f.Show();

     

     

     

    Saturday, April 5, 2008 10:44 PM
  •  

    CheckForIllegalCrossThreadExceptions is not a best practice since exception may propagate at any point in time.

    In addition, in case of if this would have been Parallel lib then definitely exception will be wrapped in Thread Scheduler unhandled exception and will propagate on finalize/before.  

     

    In concise, the best way to capture and continue would be following

    if (ostatus.richTextBox2.IsHandleCreated)
       then call your Invoke/BeginInvoke
    
    


    Sreejith S S Nair sreejithssnair@hotmail.com
    Tuesday, June 7, 2011 11:39 AM