This course - Adding Custom Controls Directly with Code - Tutorial 2

v 1.1 - last updated: 08/07/2006 - added step 4

Instead of using the Windows Forms Designer and Toolbox as in the previous tutorial, in this tutorial you manually add a custom control to a Windows application and then write code to instantiate the control on a form. There are eight steps...

  1. Create a Windows Application project called CustomTutorial:


     
  2. Add a User Control class to the project:


     
  3. Rename the control to RandomLabel.cs and click OK.


     
  4. Change the class declaration in file RandomLabel.cs to inherit from a more specific control.  Change this:
public partial class RandomLabel : UserControl

to this:

public partial class RandomLabel : System.Windows.Forms.Label
  1. Modify the code as follows (copy code from this plain text file:
       public RandomLabel()
       {
           InitializeComponent();
           Random r = new Random();
           this.Text = r.Next(100).ToString();
           this.BackColor = Color.Yellow;
       }
       
  2. Add the Form1_Load event to Form1.cs; to do this, open Form1 in the designer and double-click somewhere on the form. Modify the Form1_Load method as follows (copy code from this plain text file):
       private void Form1_Load(object sender, EventArgs e)
       {
           for (int i = 0; i < 10; i++)
           {
               RandomLabel mylabel = new RandomLabel();
               this.Controls.Add(mylabel);
               mylabel.Location = new Point(15, i * 25);
               mylabel.Size = new Size(50, 20);
               System.Threading.Thread.Sleep(300);
           }
       }
       
  3. Close and save both files and try to build the project. You'll probably get a compile error--just click on the error to open the code to the error location, and comment out the offending line of code as shown below and rebuild (this seems to be a bug):


     
  4. Now build and run the project and you should see this (with different random numbers):



Visitors: Hit Counter