Microsoft & .NET ASP ASP.NET Tip: Control the Layout of Your Input Forms

ASP.NET Tip: Control the Layout of Your Input Forms

Although many of your input forms will have a fixed number of fields, in some cases you’ll need to vary the number and configuration of your controls. This article demonstrates how to control the layout of your form using a Repeater control and the ItemDataBound event to set various attributes on the controls.


<asp:Repeater ID=”rptFields” runat=”server”>
<td align=”right” ID=”tdPrompt” runat=”server”
nowrap><%# Eval(“Prompt”) %>:</td>
<td><asp:TextBox ID=”txtValue” runat=”server” />
<input type=”hidden” id=”hdnFieldID”
value='<%# Eval(“pkFieldID”) %>’
runat=”server” /></td>


pkFieldID Primary Key, integer
Prompt String, contains the prompt to prefix the field with
MaxLength Integer, indicates maximum number of characters for the field
IsRequired Bit, indicates whether field is required


rptFields.DataSource = fieldsDataTable;


void rptParameters_ItemDataBound(object sender,
RepeaterItemEventArgs e)
if (e.Item.ItemType != ListItemType.Item && e.Item.ItemType
!= ListItemType.AlternatingItem)
DataRow dr = ((DataRowView)e.Item.DataItem).Row;
HtmlTableCell td = (HtmlTableCell)e.Item.FindControl(“tdPrompt”);
if (Convert.ToBoolean(dr[”IsRequired”]))
td.Attributes[”class”] = “popupreq”;
td.Attributes[”class”] = “popuptext”;
TextBox txt = (TextBox)e.Item.FindControl(“txtValue”);
txt.MaxLength = Convert.ToInt32(dr[”MaxLength”]);

The first thing you do is make sure that you are looking at an “Item” or “Alternating Item” template. This is because the ItemDataBound event handler is called for the Header and Footer templates, which you don’t care about for this code. You then get the DataRow for the current item being bound. Next, you find the table cell that contains the prompt text and change the style to either ‘popupreq’ or ‘popuptext’. In this example, the popupreq style uses bold face, while popuptext uses a non-bold font.



foreach (RepeaterItem ri in rptParameters.Items)
hdn = (HtmlInputHidden)ri.FindControl(“hdnFieldID”);
txt = (TextBox)ri.FindControl(“txtValue”);
// Read hdn.Value or txt.Text for persistence code

The reason you stored the field ID is because this data will generally need to be put into a table related to the data being edited. The easiest way I’ve found to do this is to fill the hidden field with the field’s number, which you can use later in a stored procedure or other method to save the field’s data to the database.

About the Author


Latest Posts

Related Stories