Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

WebForms Automatic Generation Using Reflection (1)

0.00/5 (No votes)
22 Jun 2005 1  
Describes how to generate a WebForm using reflection from a class.

Introduction

This is the first of a series of articles about code generation of Web Forms.

The idea is very simple. For the following class:

enum ArticleRating
{
   Bad, Good, Excelent
}
class Feedback 
{
    public string Name;
    public string Email;
    public string Comments;
    public ArticleRating Rating;
}

we want the following Web Form to be generated:

<TABLE><TBODY>
<TR><TD>Name:</TD><TD><INPUT id="name"></TD></TR>
<TR><TD>Email:</TD><TD><INPUT id="email"></TD></TR>
<TR><TD>Comments:</TD><TD><input id="comments"></input></TD></TR>
<TR><TD>Ratings:</TD><TD><SELECT id="ratings">
<OPTION selected value="0">Bad</OPTION>
<OPTION value="1">Good</OPTION>
<OPTION value="2">Excellent</OPTION>
</SELECT>
</TD>
</TR>
</TBODY></TABLE>

How can we do this?

There are two ways of doing this:

  • Using Serialization, you can serialize this class and use XSLT for formatting, or just play with the DOM generated.
  • Using Reflection, to explore the class members and infer the type of control to generate.

I prefer to use Reflection because I can add flexibility to it. For example:

[FormControl(Type="RadioGroup")] 
enum ArticleRating { Bad, Good, Excelent } 
[Form(Submit="OK",Clear="Clear",Action="dofeedback.aspx")] 
class Feedback 
{ 
   public string Name; 
   public string Email; 
   [FormControl(Type="TextArea", 
         Caption="Please Write Your Comments", 
         CaptionPosition="Over")] 
   public string Comments; 
   public ArticleRating Rating; 
}

This will generate the following form:

<TABLE><TBODY>
<TR><TD>Name:</TD><TD><INPUT id="name"></TD></TR>
<TR><TD>Email:</TD><TD><INPUT id="email"></TD></TR>
<TR><TD colspan="2">Please Write Your Comments:</TD></TR>
<TD><textarea id="comments"></textarea></TD></TR>
<TR><TD>Ratings:</TD><TD>
<input type="radio" value="0">Bad</input>
<input type="radio" value="0">Good</input>
<input type="radio" value="0">Excelent</input>
</TD>
</TR>
</TBODY></TABLE>

That's the idea....

I request you to read the second part of this series.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here