ASP.NET Tip: Creating a Form Using PlaceHolder Controls
Field
Description
pkParameterID
Primary key
Prompt
Text to display next to control
DataType
Text field with the value 'String' or 'TF' in it (This will let you determine which control to show.)
You then can create a simple form like this one:
<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="test.aspx.cs" Inherits="test" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-
transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Repeater ID="rptFields" runat="server">
<HeaderTemplate>
<table>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td><%# Eval("Prompt") %>:</td>
<td><asp:PlaceHolder ID="plControl" runat="server" />
<input type="hidden" id="hdnFieldID"
runat="server"
value='<%# Eval("pkParameterID") %>' /></td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
<p align="center"><asp:LinkButton ID="btnSubmit"
runat="server">Submit Data</asp:LinkButton></p>
</div>
</form>
</body>
</html>
The code behind for this page looks like this:
public partial class test : System.Web.UI.Page
{
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
rptFields.ItemDataBound +=
new RepeaterItemEventHandler(rptFields_ItemDataBound);
}
protected void Page_Load(object sender, EventArgs e)
{
Database db = new Database("(local)", "test", "sa", "dev1227");
AddControls(db);
db.Close();
}
private void AddControls(Database db)
{
DataTable dt = db.GetDataTableAdhoc("SELECT * FROM Parameters
ORDER BY pkParameterID");
rptFields.DataSource = dt;
rptFields.DataBind();
}
void rptFields_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType != ListItemType.Item && e.Item.ItemType
!= ListItemType.AlternatingItem)
return;
DataRow dr = ((DataRowView)e.Item.DataItem).Row;
PlaceHolder pl = (PlaceHolder)e.Item.FindControl("plControl");
switch (dr["DataType"].ToString().ToLower())
{
case "string":
TextBox txt = new TextBox();
txt.ID = "txtField" + dr["pkParameterID"].ToString();
pl.Controls.Add(txt);
break;
case "tf":
CheckBox chk = new CheckBox();
chk.ID = "chkField" + dr["pkParameterID"].ToString();
pl.Controls.Add(chk);
break;
}
}
}
No comments:
Post a Comment