views:

94

answers:

4

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)
{
}
+2  A: 

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.

womp
Are you sure you have a Page as well...lol Couldn't help myself.
rick schott
As much ribbing as the OP is getting, it's possible to have a null form. Consider Page classes that are constructed entirely via code, and then have an ASPX inherit from them. The base class might have virtual functionality that would rely on child classes having a form.
womp
A: 

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...

Daniel
A: 

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.

David Brunelle
A: 

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.

Aaron Daniels