Thursday, May 21, 2009

Multiple Form Tag with runat=Server

Many ASP.NET user believe that there can be only one Form tag with runat=Server, this is party true,there can be multiple form with runat=Server but only one can be visiable at a time.

Lets evaluate:

Create a aspx page and put two form tag with runat=Server like below:

<form id="form1" runat="server">
</form>

<form id="form2" runat="server">
</form>

Now compile the application, you won't get any error.

Now run the application, you will get below error

"A page can have only one server-side Form tag."

Now add a panel and set visible property to false of the panel

<asp:Panel Visible="false" ID="Panel1" runat="server">
<form id="form1" runat="server">
</form>
</asp:Panel>
<form id="form2" runat="server">
</form>

Now compile and run the application. It will run without any error.

Lets put other form also in a panel and add a button on each form tag.

<asp:Panel Visible="false" ID="Panel1" runat="server">
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Button in Form1"
onclick="Button1_Click" />
</div>
</form>
</asp:Panel>
<asp:Panel ID="Panel2" runat="server">
<form id="form2" runat="server">
<div>
<asp:Button ID="Button2" runat="server" Text="Button in Form2"
onclick="Button2_Click" />
</div>
</form>
</asp:Panel>

Now we will show and hide form on button click, copy and paste below code on code behind.

protected void Button2_Click(object sender, EventArgs e)
{
Panel2.Visible = false;
Panel1.Visible = true;
}
protected void Button1_Click(object sender, EventArgs e)
{
Panel1.Visible = false;
Panel2.Visible = true;
}

Now when you you can move to different form tag with the button click without any error.

Happy Coding :)

2 comments:

pallavi.v Vinayaka said...

thanks for this solution, still i didn't get solution. i use 2 form tags in asp it give the error same as u told.

pallavi.v Vinayaka said...

thanks for this solution, still i didn't get solution. i use 2 form tags in asp it give the error same as u told.

Site Meter