Adding a component dynamically
WebMap provides a built-in mechanism to new controls during the runtime execution without having to directly modify the front-end layer of the application, however, this mechanism has some requirements that need to be met.
The control must not be declared in the front-end application.
Its name must be unique.
The Add container logic must be invoked outside the InitializeComponent method.
The following properties are strictly necessary:
Name
Position (Top, Left)
Size (Width, Height)
The control must exist in both the front-end components and the back-end models.
Adding a new control step by step
To be able to add a new control dynamically the following steps must be made.
Step 1. Adjust the current container to allocate the new control.
This process could be made in both the back-end application by directly modifying its source code or in the front-end by applying style changes. For this scenario the modification will be directly applied in the back-end application.
In this case the new logic will be added into the application constructor.
public Form1()
{
InitializeComponent();
this.Load += (obj, e) => this.Size = new System.Drawing.Size(this.Size.Width + 150, this.Size.Height);
}
The result of the code modification will be reflected into the application the next time the back-end gets compiled.
Step 2. Once the control container has been modified accordingly, it is time to add a new instance for the desired control.
For the following example a new method (CreateNewButton) will be added, this method contains the necessary logic to create a new button instance, including its required properties needed to render in the front-end.
private void newButton_Click(object sender, System.EventArgs e)
{
/*…some logic…*/;
}
private Mobilize.Web.Button CreateNewButton()
{
return new Mobilize.Web.Button
{
Size = new System.Drawing.Size(85, 25),
Top = 10,
Left = this.Size.Width,
Name = "NewButton",
Text = "New dynamic button",
Click = new EventHandler(newButton_Click)
};
}
Step 3. Lastly the only remaining step is to add the newly created control into the list of the current controls included in its container
public Form1()
{
InitializeComponent();
this.Load += (obj, e) => this.Size = new System.Drawing.Size(this.Size.Width + 150, this.Size.Height);
this.Controls.Add(this.CreateNewButton());
}
Step 4. Compile the back-end code and the new control should now be available to use.
Last updated
Was this helpful?