Lukasz 0 Newbie Poster

Platform :

            NET , Framework 1.1, VS 2003

Example scenario :

             I have a Panel with few TextBox'es on it.  
            On Leave event I'm trying to delete all controls on the Panel 
            and add new controls. Of course before deleting I deatached lost focus event. 

Problem ( It only occure when user use mouse to navigate ! There is no problem when use TAB key. ) :

  • Application losing focus and user can't close it !
  • Sometimes NullException occure

Complete code :

using System;
using System.Windows.Forms;

namespace WindowsApplication3
{
 public class Form1 : System.Windows.Forms.Form 
   {
  private System.ComponentModel.Container components = null;

  public Form1() {
   InitializeComponent();
         AddControls();
  }

  protected override void Dispose( bool disposing ) {
   if( disposing ) {
    if (components != null) {
     components.Dispose();
    }
   }
   base.Dispose( disposing );
  }

  private void InitializeComponent() {
   this.components = new System.ComponentModel.Container();
   this.Size = new System.Drawing.Size(300,300);
   this.Text = "Form1";
  }

      [STAThread]
  static void Main() {
   Application.Run(new Form1());
      }

      private void AddControls() {
         for ( int i = 0; i < 2; i++) {
            TextBox tb = new TextBox();            
            tb.Dock = DockStyle.Top;
            tb.Leave += new EventHandler(tb_Leave);
            this.Controls.Add( tb );
         }
      }

      private void tb_Leave(object sender, EventArgs e) {
         foreach ( TextBox tb in this.Controls ) {
            tb.Leave -= new EventHandler(tb_Leave);
         }
         this.Controls.Clear();
         AddControls();
      }
   }
}