Question

When coding an Asp.Net page, you generally add a runat attribute in the aspx:

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

Is it possible to tell in the code behind if the user hasn't done this i.e. they only did this:

<form id="form1">

Here the form has the id "form1" but in my case I don't know this. Code behind such as this is what I am looking for:

if(Page.HasForm)
{
}
Was it helpful?

Solution

You can only ever have one form tag with "runat=server" on it per .aspx page. All you have to do is to check to see if Page.Form is null or not. If it's null, then there's no form that has been marked to runat server.

if (Page.Form != null)
{

}

It's the runat="server" part that makes the .aspx page process an element and create a corresponding object on the server side. If a component is not running on the server, then it's not added to the page's control hierarchy.

OTHER TIPS

var v = this.Form.TagName; //gets the name of the form that is maked as runat.

Of course if its not maked as runat then your code behind won't run anyway...

When you code in C# or Visual Basic in the code page, you will not have access to the object that do not have the runat=server option set.

You can easily access all the controls from a page using the me.controls page or something of the sort (I don't know the exact code but it's close to this) and check the type of the control to get the form.

Why do you need to know that? If a page does not have a runat=server form, it can't really be used as a server page.

You'd be able to access the form from the codebehind:

Response.Write(form1.Name);

Without the runat="server", you'd just get a compiler error.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top