Show Controls Added Programmatically in Winforms App in Design View

Show controls added programmatically in WinForms app in Design view?

Does the designer run my code?

When a form shows in designer, the designer deserialize the code of your form (Form1.Designer.cs or first class in Form1.cs) and creates an instance of the base class of your form and deserialize InitializeComponent and creates controls that you declared in your class and set their properties.

So the codes in Constructor won't run. The designer only creates an instance of the base class of your form and don't look in constructor of your form.

Interesting example of how the designer works

Look at below code and pay attention to this problems:

  • Where are ;s?
  • Constructor Form111111 for Form1?
  • What is NotDefinedFunction()?
  • How can int i = "xxxxxxxxxx"?

Even if you create such file, the designer will show correctly.

using System
using System.Collections.Generic
using System.Drawing
using System.Windows.Forms
namespace Sample
{
public class Form1:Form
{
public Form111111()
{
NotDefinedFunction()
InitializeComponent()
}
public void InitializeComponent()
{
int i = "xxxxxxxxxx"
this.textBox1 = new System.Windows.Forms.TextBox()
this.SuspendLayout()
//
// textBox1
//
this.textBox1.Location = new System.Drawing.Point(0, 0)
this.textBox1.Name = "textBox1"
this.textBox1.Text = "text of text box 1";
//
// Form1
//
this.Controls.Add(this.textBox1)
this.Name = "Form1"
this.Text = "Form1"
this.Size= new Size(250,100)
this.ResumeLayout(false)
this.PerformLayout()
}
private TextBox textBox1
}
}

And you will see the form in designer:

Sample Image

How can I add controls dynamically at design time?

If you need such functionality, you can create your dynamic controls in constructor of a base class for your form, since constructor of base class will run when you open a child form in designer, then it will run at design time.

But you should know these controls are inherited and can't be changed using designer of child form.

So simply create a Form2:

public Form2()
{
InitializeComponent();
AddDynamicControls();
}

private void AddDynamicControls()
{
this.Controls.Add(
new TextBox() {
Name = "TextBox1", Text = "Dynamic", Location = new Point(100, 0) });
}

Build the project and then change base class of Form1 to inherit from Form2:

public class Form1:Form2

And the result will be:

Sample Image

Is there any other solution?

If you want to generate some controls really at design time, I think you should take a look at T4 Text Templates.

You can use t4 templates to generate code at design-time. Probably you have seen Entity Framework .tt template files. You can add new Text Template item to your project and put the logic for generating items at design-time in your t4 template.

Automate control creation in windows forms designer

According to comment by Hans Passant, all that is needed is to ask the designer environment to create the object, so the new component can be tracked.

   var host = GetService(typeof(IDesignerHost)) as IDesignerHost;
var button = host.CreateComponent(typeof(Button), "someName") as Button;
FindForm().Controls.Add(button);

Show Dialog when entering Design Mode on Winform

You can do it in following way:

Create a base form:

public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.Load += new EventHandler(Form1_Load);
}

private void Form1_Load(object sender, System.EventArgs e)
{
if (this.DesignMode && LicenseManager.UsageMode == LicenseUsageMode.Designtime)
{
MessageBox.Show("Hello");
}
}

}

And on the second form on wards where you would like to show the message box, you will just have to inherit it, like below:

public partial class Form2 : Form1
{
public Form2()
{
InitializeComponent();
}
}

and as soon as you open a form in design time, it will show you message box.

This worked for me, I hope this will help you. :)

How to select a control programmatically in design mode

WinForm Designer code is all about using designer services. In this case you need to acquire an instance of the selection service that is manifested through an object that implements the ISelectionService Interface.

You acquire a service instance through an object that implements the IServiceProvider Interface. The Control.Site Property implements the ISite Interface that in turn implements IServiceProvider.

Use the IServiceProvider.GetService(Type) Method to acquire the service and then use the ISelectionService.SetSelectedComponents Method to select the desired component(s).

Public Overrides Function OnMouseUp(g As Glyph, button As MouseButtons) As Boolean
Dim myg As MyGlyph = CType(g, MyGlyph)
Dim c As Control = myg.control
Dim selService As ISelectionService = CType(c.Site.GetService(GetType(ISelectionService)), ISelectionService)
selService?.SetSelectedComponents({c})
Return True
End Function

Winforms App Not Displaying Graphical Elements in Design Mode

So to get this shown within the designer you have to know how the designer works.

For every MyForm.cs there will automatically be a file called MyForm.Designer.cs be created. Within this Designer file there will be only one function called InitializeComponents(). This function will be called within the constructor of your MyForm.cs file.

The design viewer itself is responsible for the Designer file, so any change to this file while the design view is open would normally be discarded. Also if you put some code into the designer file that is not needed be the designer will be truncated.

So the next question is, when will this truncation happen? When you freshly open the design viewer of a form, it will read in everything from the Designer.cs file without making any changes. If you make any changes onto the form by the designer the complete file will be rewritten with all the settings already read in including your latest changes.

This behaviour can be monitored if you open the designer file also as source code view, make some little changes in design mode and afterwards take a close look at the left of the source file. There will be the changes marked with a yellow or a green marker.

Now after all this stuff of informations, you can try the following procedure to get your code into the designer:

  • Open the design view and put some simple control onto your form (e.g. TextBox)
  • Save and close the design view and open the Designer.cs file as source file
  • Copy all your variables name of your controls at the end of the file, right below the textBox1 line
  • Copy all your control property settings within the InitializeComponent() function right below the property settings of the TextBox
  • Copy all your control constructors to the top of the file, right below the constructor of the TextBox
  • Save the file and open your form in design view
  • Select the dummy TextBox on the design view and delete it

    • This change within the DesignView leads to a complete rewrite of the designer.cs file, ordering all your manually added stuff the right way.

So this is the way to go. Last but not least another little trick:

Every programmer uses the using-statement to not write the whole path to every class (like System.Windows.Forms.TextBox), but the designer writes always the whole path. To make it a little easier for your copy and paste session you can also add a using statement at the top of the file. After saving and changing something in Design View all this stuff will be re-written automatically. So you don't need to add all this paths manually while your adding your stuff to the Designer.cs file.

Best Practices: Add controls in Design-Time or Run-Time

In general, there is no difference between using the designer or defining the control variable in the code, because the designer also provides some equivalent C# code after dragging & dropping the control into your form. You can see this auto-generated code in the files with *.Designer.cs prefix and you may edit and change the auto-generated code

But in some specific cases you may prefer to define your controls manually in the code.

for example:

  1. Sometimes count, arrangement and configuration of the controls can be changed dynamically during run-time. for example, there is a config file beside your application and some changeable parameters in this config file determine count and properties of some controls in your GUI.
  2. You may prefer to limit scope of definition of your control to a single function instead of allover the namespace or allover your form class.

How to implement events for the controls which are programmatically added in the view?

Use the activated event:

Btn1.Activated += Btn1_Activated;

or

Btn1.Activated += (sender, e) => {
// code here
};

Winforms - how to show/hide elements in designer?

Several options here:

  1. Use the Document Outline view (View --> Other Windows --> Document Outline) to select the panel you care about. You can right-click on it and choose Bring to Front to put it in front of everything else.
  2. Though it's probably not relevant to what you're doing, you might consider using a TabControl, which you can mess with visually at design time. This is only a reasonable solution if you want your users to be able to manually change which panel they're viewing.
  3. Consider moving your panels into custom UserControl classes and work on them separately. If the content and logic of these panels is reasonably self-contained then you may want to do this anyway just to better restructure your code.

Addendum: You can also use a hack that makes a TabControl's tabs invisible to the user. Put a TabControl on your form, and at run-time set the ItemSize height to 1. This makes it (almost) impossible for the user to change the tabs on their own, but still allows you to change the visible tab in the designer.

myTabControl.ItemSize = new Size(myTabControl.ItemSize.Width, 1);

Note that I called this a hack for a reason: TabControls were not meant to be used this way. It's something that appears to work, but like all hacks it may break at any time so you should only do it as a last resort (and don't blame me if it causes headaches later on...). In short, I do not recommend this hack, I only offer it as a possibility.

Adding new user control programmatically in windows forms

You need to add your user control to the display surface of the main form (or another container already present)

    MainScreen home = new MainScreen();
home.Show();
EntrySuggestion t_ES = new EntrySuggestion();
home.Controls.Add(t_ES);


Related Topics



Leave a reply



Submit