Run-time Error: Control ‘controlname’ of type ‘Button’ ‘TextBox’ ‘GridView’ ‘CheckBox’ must be placed inside a form tag with runat=server Asp.Net C# VB.Net

I found this error in Asp.Net when i am trying to add a control dynamically in the page. The error is Control ‘controlname’ of type ‘Button’ must be placed inside a form tag with runat=server. The error comes when you trying to add a control like GridView, Button, TextBox, RadioButton, RadioButtonList, CheckBox, CheckBoxList out side the form tag of your aspx page in runtime or dynamically. There were another reason you may add those controls in your page under form tag but when you open it in other editor like dreamweaver and drag those controls then might be a chance that the control positioned outside the form tag. This type of problems solution is, just place those controls inside the form tag. The error is:

control must be placed inside a form tag with runat server

Simulate the Error First:
C# Code:

    protected void Page_Load(object sender, EventArgs e)
    {
        Button cmd = new Button();
        cmd.Text = "Click Me";
        // Error comes from this line
        this.Controls.Add(cmd);
        cmd.Click += new EventHandler(Dynamic_Method);
    }

    private void Dynamic_Method(object sender, EventArgs e)
    {
    }

VB.Net Code:

    Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        Dim cmd As New Button()
        cmd.Text = "Click Me"
        ' Error comes from this line
        Me.Controls.Add(cmd)
        AddHandler cmd.Click, AddressOf Dynamic_Method
    End Sub

    Private Sub Dynamic_Method(sender As Object, e As EventArgs)
    End Sub

Now run the project. You will get the said error.

Error Resolution:
C# Code:

    protected void Page_Load(object sender, EventArgs e)
    {
        Button cmd = new Button();
        cmd.Text = "Click Me";
        //Resolution
        this.Form.Controls.Add(cmd);
        cmd.Click += new EventHandler(Dynamic_Method);
    }

    private void Dynamic_Method(object sender, EventArgs e)
    {
    }

VB.Net Code:

    Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        Dim cmd As New Button()
        cmd.Text = "Click Me"
        'Resolution
        Me.Form.Controls.Add(cmd)
        AddHandler cmd.Click, AddressOf Dynamic_Method
    End Sub

    Private Sub Dynamic_Method(sender As Object, e As EventArgs)
    End Sub

Now run the project. The error will be resolved.

Good to Read:
Runtime Add Dynamic Button Control and Handle Click Event in ASP.Net C# VB.Net

Download Code Example C#        Download Code Example VB.Net

Posted in .Net, Asp.net, C#, VB.Net

Leave a Reply

Your email address will not be published. Required fields are marked *

     

*