How to add link Labels at run time in Windows form - c#

I have been making a Windows Form Application in C# using the Visual C# 2008 IDE.
There are basically two forms in my application. One is created at Runtime and it's layout is undefined and the second one's predefined.
Now, I have been adding form elements using the toolbox provided and don't have any idea how to add them using written code(not using toolbox). I want to add n number of Labels to the second form which is undefined. n can be anything(decided at runtime, depending on the user's input). Can anybody tell me what is the efficient way to do this?

Just a quick example of a "dynamic control" being created at run-time and added to the form:
Label lbl = new Label();
lbl.Text = "Hello World!";
lbl.Location = new Point(100, 25);
this.Controls.Add(lbl);
You can replace "this" with the container to add it to, like "panel1" for instance. For containers that have their own layout engine, like a FlowLayoutPanel, then you wouldn't need to specify a Location().

Create a new LinkLabel(), set its properties (in particular, text and position), then add it to the Controls collection of your form or any panel.
You may also want to add event handlers, and store them somewhere (probably in a List<T>) so you can change or remove them later.

Create one in the designer, configure it's properties as you wish. Then go to the designer file, which name is like Form1.Desiner.cs, copy the code related to your LinkLabel (find everything with text search) and paste it where you wish :)

Related

How to create tab pages content dynamically in windows forms?

I am using windows form to build an app that draws the form controls based on the connected device dynamically. So I have a tab control and when the user select tab3 for instance the tab page content will be drawing based on connected device for example add two text boxes and a button. How can I do this. I would like also to know how to position those controls after they are created.
private void tabPage3_Click(object sender, EventArgs e)
{
TextBox text = new TextBox();
this.tabPage3.Controls.Add(text);
}
As you just stated, you create your Controls like in your example. Positioning is achieved by the Left and Top Properties of your freshly created control. BUT, my advise is, it will be easier to use predefined UserControls and add them dynamically, because I think you don't have nearly unlimited types of devices.
If you are curious how Visual Studio Designer is creating those code, just look up Designer.cs in InitializeComponent()

How to create a ToolStripDropDownButton?

I want to create a ToolStripDropDownButton which looks like the below image
But when I tried to search for ToolStripDropDownButton control in the Toolbox I was unable to find it because, after some googling, I found out that it is a class not namespace.
Then I googled out the code below
ToolStripDropDownButton dropDownButton1 = new ToolStripDropDownButton();
ToolStripDropDown dropDown = new ToolStripDropDown();
dropDownButton1.Text = "A";
dropDownButton1.DropDown = dropDown;
dropDownButton1.Height = 200;
dropDownButton1.Width = 200;
Set the drop-down direction.
dropDownButton1.DropDownDirection = ToolStripDropDownDirection.Left;
// Do not show a drop-down arrow.
dropDownButton1.ShowDropDownArrow = false;
Controls.Add((Control)dropDownButton1); //Doesn't work
But the last line of code is not valid and gives runtime error
Cannot convert type 'System.Windows.Forms.ToolStripDropDownButton' to
'System.Windows.Forms.Control'
Can someone tell me how to add such a button in C# Windows Form or what am I missing in the code?
Platform : VS2008 Express (i know it's old)
The error message says that ToolStripDropDownButton is not a Control and thus, you can't add it to your form directly.
ToolStripDropDownButton and other tool strip items only work as a part of a ToolStrip. So, you need to put a toolstrip on your form, then you can add items to it.
Code example, if you want to do it programmatically:
ToolStrip toolStrip = new System.Windows.Forms.ToolStrip();
toolStrip.Items.Add(dropDownButton1);
Controls.Add(toolStrip);
It looks like your code comes from ShowDropDownArrow example on MSDN. Check out the complete code.
Also, you can do it in a form designer in Visual Studio. Look for ToolStrip in a toolbox.
Relevant links:
MSDN: How to: Create a Basic Windows Forms ToolStrip with Standard Items
Using the Designer
MSDN: How to: Add ToolStrip Items Dynamically
C# Corner: ToolStrip in C#
StackOverflow: Windows.Forms button with drop-down menu - discussion of alternative ways to implement this kind of control. One of the answers suggests to use a standalone ToolStrip.

Setting the control's parent in form designer

This MSDN article offers some good advice about manually customising the form designer to improve performance:
Reduce the number of method and property calls on controls during startup. For example, Controls.Bounds is a better option than calls to Control.Location and Control.Size.
Create the form from the top down. In nested control hierarchies, set the parent property of containers (using the above rule) before adding controls to the container. As in the BigForm application, the panels had their parent property set to the form before the 40 controls were connected to the panel. If further containers exist lower in the hierarchy, the same changes should be applied.
I have followed the 1st bit of advice, replacing:
this.MyControl.Location = new System.Drawing.Point(5, 5);
this.MyControl.Size = new System.Drawing.Size(630, 90);
with:
this.MyControl.Bounds = new System.Drawing.Rectangle(5, 5, 630, 90);
This resulted in a super 20% (about 200ms) speed-up on one form. I'm trying to follow the 2nd bit of advice and not quite sure how to proceed. The Designer.cs file contains code like this:
this.Controls.Add(this.pnlHeader);
but not the code I was expecting (according to the example):
this.pnHeader.Parent = this; // Not in the Designer
The code this.Controls.Add(this.pnlHeader); appears at the bottom of InitializeComponent. Is the advice suggesting moving the code to the top or something else entirely?
EDIT #2
i found this msdn article which explain the issue as following:
Another method for improving performance is to initialize the controls
in the control tree top-down. For example, if you have a panel control
with many controls in it, create the panel first, and then add the
controls to the panel. Also, setting the parent property of the
control instead of adding to the Controls collection can improve
performance.
For example, consider adding a textbox to a panel's control collection:
Before optimization:
// Create a new panel and textbox control
Panel panel1 = new Panel();
TextBox textBox1 = new TextBox();
// Set the Text property of the TextBox control
textBox1.Text = "My Text";
// Add the TextBox to the Panel's control collection
panel1.Controls.Add(this.textBox1);
// Add the Panel to the Form's control collection
this.Controls.Add(panel1);
//... subsequent controls
Optimizing this code snippet using the top-down and parenting techniques results in the following snippet:
After optimization:
// Create a new panel and textbox control
Panel panel1 = new Panel();
TextBox textBox1 = new TextBox();
// set parents from top to down
this.panel1.Parent = this;
this.textBox1.Parent = this.panel1;
// Set properties of child control (cause repainting only once)
textBox1.Text = "My Text";
//... subsequent controls
This can make a big difference with a deeply nested control hierarchy.
Optimizing the code in the InitializeComponent method by creating
the controls top-down and re-parenting them resulted in a performance
improvement of about 50% over the default Forms Designer generated
code!
Following on from the answer from S.Serp here are some observations to be aware of:
Replacing Location and Size with Bounds resulted in an average boost of ~15% for form loading.
Replacing Controls.Add with Parent resulted in a further boost of ~5-10% (for an impressive total of ~20-25%).
As Sefe points out, manually editing the Designer.cs file is usually only appropriate where you are not making changes in the Designer very often. Any changes made in the Designer will overwrite your manual code. Be warned! This is not a disaster, you simply lose the boost. Either live with the slower form loading or redo the manual changes.
Be careful to put the Bounds call after setting Multiline = true; on TextBox controls (if enabled). If you set it before, your control will (unhelpfully) be resized to a single line.
Be careful with ensuring each child control has the parent set correctly! Open all forms in the Visual Studio Designer after manually editing InitializeComponent to see that everything is kosher...but don't edit anything otherwise your changes will be deleted.
The lines...
this.Controls.Add(this.pnlHeader);
...and...
this.pnHeader.Parent = this;
...are equivalent. The control trees they produce are identical. And you should not change the auto-generated code. Your changes will be overwritten the next time the designer writes its updates.
You usually don't have to worry about the designer-generated code. You can concentrate on your part and assume the designer is correct.

How to make changing "screens" in c#

I'm new in C#, and I wanted to know if there was any way to show a screen with certain elements, and then with the click of a button, switch to another screen, similar to an installer.
From my experience in Java, I would just use a few JPanels and then hide only the one i want visible.
However, I'm new to C# forms and it's very different from Java swing. Anyone understand my problem and can tell me pretty much how this works? Thanks.
Simple approach
Just use a Grid with multiple Grids inside of it. Set the Visibility property of each internal Grid (except the first one you want to show) to Hidden or Collapsed, and then set them to Visible when you want to display them.
Better approach
Create a class for each section, each of which derives from the same parent class. Create a DataTemplate for the parent class, then just have instances of the template load into the original Grid through a ContentPresenter.
You can try this creating new forms. From my experience I've tried this:
Form2 formTwo = new Form2(); // creates instance
formTwo.Show(); // displays the new form
this.WindowState = FormWindowState.Minimized; // minimizes previous form
this.ShowInTaskbar = false; // hides it from taskbar
Keep in mind that this does not close the previous form. I would recommend setting ShowIntaskbar as True if you don't mind the user seeing the form minimized.
EDIT: If you want to show new elements I suggest you can try adding a new Form class to the project then using the designer.

Winform Templating System like ASP.NET MasterPage or MS Access SubForm

Does a Winform Framework exist for something similar to ASP.NET Masterpage or MS Access SubForm ?
With MS Access SubForm you can do like ASP.NET Masterpage. It's a huge loss of time with Winform when having to create a lot of complex form. You have to compensate with either Code Generation which create code duplication or do Runtime Dynamic Form which is much more difficult.
I searched on the Internet but can't find any.
The closes thing to Master Pages is Form Inheritance. It is regular class inheritance but also supported by the Designer. To try it:
1) Add a form with Ok and Cancel Buttons, Build project (essential)
2) Choose Project, Add new item, Windows and then the Inherited Form template. Pick the Form from step 1) as the base Form. Add some controls.
3) Repeat step 2) a few times
4) make some Buttons to show the Forms, Build and Test
5) Go back to the Form from 1) and change a few things (Background), run again
Your other tool are UserControls, they work much the same as in ASP.NET. You develop them like Forms and apply them as Controls.
You can add forms to a form, or to a panel on a form.
public Form1()
{
InitializeComponent();
Form2 embeddedForm = new Form2();
embeddedForm.TopLevel = false;
Controls.Add(embeddedForm);
embeddedForm.Show();
}
You will need to set the FormBorderStyle to None, unless you want to have an actual moveable form inside your form.
I was in a bit of a hurry at the time of posting, but Henk is right. You should consider creating a user control for this instead. Not to be confused with a custom control, which is intended for when you need to do your own drawing instead of using collections of standard Windows controls.

Categories

Resources