How to add components at run time in C#

No.of Views726
Bookmarked0 times
Downloads 
Votes0
By  hamzka   On  17 Apr 2010 01:04:57
Tag : CSharp , How to
How to add components at run time in C#
emailbookmarkadd commentsprint

Images in this article missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at info@codegain.com

 

Introduction

how to add buttons at run time by clicking on a button in .net.

 

Implementation

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace addCompRunTime
{
    public partial class Form1 : Form
    {

        public Form1()
        {
            InitializeComponent();
        }

        private int Y = 13;
        private int X = 13;
        private Button b;
        private int i = 0;
        private void button1_Click(object sender, EventArgs e)
        {
            b = new Button();
            b.Text = "btn" + i.ToString();

            b.Name = b.Text;
            b.Width = 70;
            b.Height = 33;
            b.Top = Y;
            b.Left = X;
            Y += 47;

            if (b.Top + 46 > this.Height)
            {
                X += 104;
                Y = 13;
            }
            else
            {
                this.Controls.Add(b);
                b.Show();
            }

            i++;
            //if(i%2==0)
            b.Click += new System.EventHandler(this.b_Click);
            Thread.Sleep(164);

        }
        private void b_Click(object sender, EventArgs e)
        {
            Button btn = (Button)sender;
            MessageBox.Show(btn.Text /* btn.Top.ToString() */ );

        }

    }

}

 

Sample Project Source

Download source files -33 kb

 
Sign Up to vote for this article
 
About Author
 
hamzka
Occupation-Not Provided
Company-Not Provided
Member Type-Fresh
Location-Not Provided
Joined date-23 Jan 2010
Home Page-Not Provided
Blog Page-Not Provided
 
 
Other popularSectionarticles
Comments
By:AralmoDate Of Posted:2/23/2011 8:18:57 AM
a Control is not a component
Post is ok but you are not adding components but controls into your form. They are two very different things.
Leave a Reply
Title:
Display Name:
Email:
(not display in page for the security purphase)
Website:
Message:
Please refresh your screen using Ctrl+F5
If you can't read this number refresh your screen
Please input the anti-spam code that you can read in the image.
^ Scroll to Top