.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
david stephan

Home >> Code Snippets >> Windows Form Controls >> Post New Resource Bookmark and Share   

 Subscribe to Code Snippets

Adding Removing Controls On The Runtime and Getting its Values.

Posted By:Hefin Dsouza       Posted Date: August 11, 2009    Points: 10    Category: Windows Form Controls    URL: http://www.dotnetspark.com  
 

Adding Removing Controls On The Runtime and Getting its Values.

 

This sample demontrates how to Add Controls on Runtime and how to remove them.
And also how to get values out of an Runtime Created Control.It Also demonstrates how to write event handlers for runtime created controls.

Controls Are Added by The Following Code..

 private void button1_Click(object sender, EventArgs e)
{
            j = j + 1;
            TextBox cntrl;
            LinkLabel labl;
            cntrl = new TextBox();
            cntrl.Text = "Text " + i.ToString();
            labl = new LinkLabel();
            labl.Name = "lbl" + j.ToString();
            labl.Text = "Remove Text Box";

            labl.Tag = cntrl;

            labl.Click += new EventHandler(RemoveControl);
            if (i < this.Height)
            {
                cntrl.Location = new Point(0, i);
                labl.Location = new Point(cntrl.Width + 5 , i);
                i = i + cntrl.Height +5;
                Controls.Add(cntrl);
                Controls.Add(labl);
            }
            else
            {
                MessageBox.Show("Cannot Add more Controls");
            }
}


Controls Are Removed by the Following Code

        public void RemoveControl(object sender, System.EventArgs e)
        {
                LinkLabel lbls=(LinkLabel)sender;
                this.Controls.Remove((LinkLabel)sender);
                this.Controls.Remove((TextBox)lbls.Tag);

        }


Values are retrived using the Following Code

     private void button2_Click(object sender, EventArgs e)
        {
            foreach (Control ctrl in Controls)
            {
                if (ctrl is TextBox)
                {
                    MessageBox.Show(((TextBox)ctrl).Text);
                }
            }
        }


Note that The Tag Property of the LinkLable Control is used to Store the information about the control next to it(TextBox) for Removing purpose only.

---------------------------
Regards Hefin Dsouza


     

Further Readings:

Responses

No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More code samples in C#, ASP.Net, Vb.Net and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend