Introduction
This is a general treatment of how to create a form on the fly and add simple objects and methods/events.
Background
I was looking around for a simple way of creating forms on the fly. There were some bits and pieces around the web but nothing that had it all in one place. Or it could be that I just stink at search engines.
What you will find below is a quick and easy way of creating said forms with objects and events. It is by no means a complete/exhaustive list, but should be enough of an example that you should be able to generate your own solutions.
Using the Code
Below is a project that has a form that contains all the necessary code. It is very repetitive, and you can create a form with any and all of these and more objects. In the case of this demonstration, I allowed only one object per instance.
One additional note - the form will gather data but makes no attempt to send it back to the calling form. Although this is a minor task, if you need assistance accomplishing it, just drop me a line. I'll fudge some code for you.
using (Form formNew - new Form())
using (Form formNew = new Form())
{
formNew.Text = "Created Form";
formNew.Size = new System.Drawing.Size(400, 200);
addCheckBox("CheckBox", 10, 25, 150, 20, formNew);
formNew.ShowDialog();
}
{
private void addCheckBox(string checkboxname, int locationL, int locationT, int sizeL, int sizeLen, Form parentForm)
{
CheckBox CKBox1 = new CheckBox();
{
CKBox1.Name = checkboxname.ToString();
CKBox1.Text = checkboxname.ToString();
CKBox1.Location = new System.Drawing.Point(locationL, locationT);
CKBox1.Size = new System.Drawing.Size(sizeL, sizeLen);
CKBox1.MouseHover += delegate(object sender, EventArgs e)
{
MessageBox.Show("this is a Hover " + CKBox1.Name);
};
parentForm.Controls.Add(CKBox1);
}
}
Points of Interest
I created this out of an application for maintaining a SQL database. Being lazy, I didn't want to have to code for the schema or simple validation. I originally pulled the schema via a system stored proc. Then I stored the name, length, and type in a string
array for processing. All these goodies have been scrubbed out.
This example isn't a revelation and shouldn't be anything new. Nor is it meant to be bulletproof. But hopefully, it will be of some use.
History
-
26th March, 2014: Initial version