简体   繁体   中英

How to deal with create window handle exception when add custom control to a panel in C#?

Currently I have a program to display some item information. What I have is a com box to exercise different categories, and one panel to display items per selection in the com box .

I created my own custom control to display, but when I add it to a panel dynamically, it causes a Win32 Exception which is Create Window handle Error .

After testing several times, I noticed that once the panel has listed 1800 custom controls in total, the exception occurs. Is there anyone who can resolve this issue? Thanks.

private void DisplayItems(List<ITEM_DATA> ItemList)
{
    DisposeControls();
    int total = ItemList.Count;

    ItemDisplayer itemDisplayer = null;
    Application.DoEvents();
    for (int i = 0; i < total / 4 + 1; i++)
    {
        for (int j = 0; j < 4; j++)
        {
            int m = (i * 4) + j;
            if (m >= total)
            {
                return;
            }
            itemDisplayer = new ItemDisplayer(ItemList[m], ref labItemName);
            itemDisplayer.Size = new Size(240, 80);
            itemDisplayer.Location = new Point(240 * j, 80 * i);
            itemDisplayer.Name = "itemDisplayer" + Convert.ToString(m);
            pnlItems.Controls.Add(itemDisplayer); 
        }
    }
}

Just want to confirm. After spend a while to figure out where this issue happened. I realized that the User Object has reached the limit 10000. And i just resolved that problem by dispose user control properly.

I re-implement dispose method in my custom control class.

 // Flag: Has Dispose already been called?
   bool disposed = false;
   // Instantiate a SafeHandle instance.
   SafeHandle handle = new SafeFileHandle(IntPtr.Zero, true);

   // Public implementation of Dispose pattern callable by consumers.
   public void Dispose()
   { 
      Dispose(true);
      GC.SuppressFinalize(this);           
   }

   // Protected implementation of Dispose pattern.
   protected virtual void Dispose(bool disposing)
   {
      if (disposed)
         return; 

      if (disposing) {
         handle.Dispose();
         // Free any other managed objects here.
         //
      }

      // Free any unmanaged objects here.
      //
      disposed = true;
   }

According to enter link description here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM