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.
The example form has a simple table that includes the following Repeater control:
<asp:Repeater ID="rptFields" runat="server">
<ItemTemplate>
<tr>
<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>
</tr>
</ItemTemplate>
</asp:Repeater>
Behind the scenes, a table called FormFields (or something appropriate) has these fields:
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;
rptFields.DataBind();
The key event handler to make this work is the ItemDataBound event handler. It looks something like this:
void rptParameters_ItemDataBound(object sender,
RepeaterItemEventArgs e)
{
if (e.Item.ItemType != ListItemType.Item && e.Item.ItemType
!= ListItemType.AlternatingItem)
return;
DataRow dr = ((DataRowView)e.Item.DataItem).Row;
HtmlTableCell td = (HtmlTableCell)e.Item.FindControl("tdPrompt");
if (Convert.ToBoolean(dr["IsRequired"]))
td.Attributes["class"] = "popupreq";
else
td.Attributes["class"] = "popuptext";
TextBox txt = (TextBox)e.Item.FindControl("txtValue");
txt.MaxLength = Convert.ToInt32(dr["MaxLength"]);
}
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
}
No comments:
Post a Comment