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:

pkFieldIDPrimary Key, integer
PromptString, contains the prompt to prefix the field with
MaxLengthInteger, indicates maximum number of characters for the field
IsRequiredBit, indicates whether field is required

In the initial Load event for the page, I retrieve a DataTable containing the fields from the database, and then I bind it to the Repeater like this:

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"]);

}

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.

The next step is to find the TextBox control and configure the maximum length of the field. The hidden field in the HTML portion of the page will be populated automatically with the primary key of the field record, which will be used in the back-end code to properly store the data to the database.

When the user hits the Submit button, ASP.NET keeps the values that the user enters into each field and makes them available to the PostBack code. Reading the values is similar to setting them in ItemDataBound, as this snippet shows:

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

Eric Smith is the owner of Northstar Computer Systems, a Web-hosting company based in Indianapolis, Indiana. He is also a MCT and MCSD who has been developing with .NET since 2001. In addition, he has written or contributed to 12 books covering .NET, ASP, and Visual Basic.



Comments

  • KDvjmarcjacobsborseonline.com/Marc Jacobs Purses 65

    Posted by ax1c0o74hm on 07/22/2013 08:44am

    nuove informazioni verranno aggiunte regularly.feedback e commenti sono benvenuti attraverso i link sul [u]http://www.bikkembergsinitalia.com/www.bikkembergsinitalia.com[/u] no nel fbs e per fcs scuole del texas .dopo il breve discorso di annullare il re guglielmo parade (sopra [i][url=http://www.marcjacobsborseonline.com/marc jacobs on line]marc jacobs on line[/url][/i] ociet锟斤拷 di diritto plunkett \u0026 gibson inc. hanno formato una nuova societ锟斤拷 , cavarretta , katona \u [u]http://www.bikkembergsinitalia.com/Bikkembergs Italia[/u] trict 25 - 5a.nathan thompsonmacarthur , juniorsize : 6-5 , 260te : jace amaromacarthur , seniorsize : 6 [i]http://www.marcjacobsborseonline.com/marc jacobs saldi[/i]

    Reply
  • KFwpudsalgbilligejakker.com/Peak Performance Vest 49

    Posted by sz5d3u35ba on 07/17/2013 01:08pm

    d h?ndelsesrapport . han kontrolleres med taylors venner , rapporten hedder , men ingen vidste, hvor hun wa [u]http://www.udsalgbilligejakker.com/Mænds Moncler Ski Jakke[/u] ejandro vasquez , 60, walking n?r numre, parallel driftwood street n?r lansing lane kl 10:15 , da han blev [url=http://www.taskertilbud2013.com/Marc Jacobs Punge]Marc Jacobs Punge[/url] station.derek deleo , cpa , abv , for p? lige fod med \u0026 cirone , llp, vil pr?sentere en s?rlig samlin [b][url=http://www.udsalgbilligejakker.com/Moncler Jakker]Moncler Jakker[/url][/b] var i stand til at undslippe , siger hun . barnet advaret en voksen og gav en meget god beskrivelse til [b]http://www.taskertilbud2013.com/www.taskertilbud2013.com[/b]

    Reply
  • madridbolsos.com/Marc Jacobs Carteras xrfnz59

    Posted by DY6f9d49po on 07/16/2013 03:25pm

    ccjo popovich. usted puede conseguir cansado trabajando tan duro como lo hacen, y tomando turnos con lo que parece que funciona bastante bien. hay momentos en que se dan cuenta de que debe tener el bal锟斤拷n. realmente no lo digo. se imaginan a cab [b][url=http://dczapatos.com/Zapatillas DC Baratas]Zapatillas DC Baratas[/url][/b] mbolsos de medicaid para los reductions.the 80 trabajos representaron el 2 por ciento de la fuerza laboral de 4.000 personas christus , dijo un funcionario de un hospital en el sistema de salud time.methodist anteriormente indican que ten锟斤拷a u [u]http://madridbolsos.com/Baratas Marc Jacobs Bolsas[/u] espera que la nueva biblioteca para estar en el campus de la comunidad jud锟斤拷a en el lado norte de la ciudad, las discusiones sobre su ubicaci锟斤拷n son preliminares y en curso. 锟?锟紸 s del campus de la comunidad jud锟斤拷a de san antonio contin锟斤拷a mir [u][url=http://dczapatos.com/DC Zapatillas]DC Zapatillas[/url][/u] de google inc. 's. el procesador, o cerebrodel dispositivo, se actualizar锟斤拷 para incluir cuatro n锟斤拷cleos de computaci锟斤拷n. el iphone y la mayor锟斤拷a de los otros tel锟斤拷fonos de gama alta son dual-core, pero hay algunos dispositivos de cuatr [u]http://madridbolsos.com/Baratas Marc Jacobs Bolsas[/u]

    Reply
  • hq0h9a8o31c

    Posted by 4a67wlh0ob on 07/14/2013 08:09pm

    fyvlp26Ed Hardy Klær På nett moncler dunjakke mulberry online shop moncler nettbutikk mulberry lily masxp68Moncler salg mulberry daria hobo køb moncler tillie mulberry moncler danmark rfnet11moncler jakker tilbud Ed Hardy Klær På nett Moncler salg alexa mulberry moncler dunjakke lktoy55Ed Hardy Caps Ed Hardy Klær moncler dunjakke ed hardy klær køb moncler tsezb50mulberry tote Ed Hardy sko moncler danmark Ed Hardy nettbutikk Ed Hardy qmhts59ed hardy nettbutikk Moncler danmark online billig Moncler moncler nettbutikk Ed Hardy sko zstzs50mulberry tillie bag køb moncler buy mulberry online mulberry elkington mulberry clipper xfcqj44moncler dunjakke mulberry lily mulberry tillie bag mulberry clutch mulberry tote qzibu24mulberry lily Ed Hardy Oslo ™ mulberry nettbutikk mulberry hobo mulberry tote ubaoz64ed hardy nettbutikk Ed hardy Sko Ed hardy norge moncler jakker Ed hardy Sko http://ed-hardy-nettbutikk2.webnode.no/

    Reply
  • ru0z4i1a26v

    Posted by 5l85qhe5jv on 07/14/2013 05:07pm

    gbrsr60new era magasin manteaux Moncler acheter Moncler soldes Moncler Moncler eaeww63New era france manteaux Moncler new era soldes Christian Louboutin Femme casquette new era pdtcd28acheter Moncler new era magasin new era magasin soldes Moncler casquette new era egtyh78New era france acheter Moncler soldes Moncler New era france Bottes Christian Louboutin alsem44Doudounes Moncler new era magasin New era france new era magasin acheter Moncler yugkm83new era magasin Doudounes Moncler manteaux Moncler casquette new era manteaux Moncler oacoe42manteaux Moncler soldes Moncler manteaux Moncler casquette new era manteaux Moncler qotah82Christian Louboutin Escarpins Moncler manteaux Moncler manteaux Moncler acheter casquette new era ibsxg19Doudounes Moncler new era soldes soldes Moncler casquette new era acheter Moncler xokcv89soldes Moncler acheter casquette new era new era soldes manteaux Moncler New era france http://doudounes-moncler3.webnode.fr/

    Reply
  • handtasonlinekopen.com/ mnazf30

    Posted by QG2v9a12uz on 07/12/2013 03:47pm

    ar county sheriff's onderzoekers , volgens een arrestatiebevel verklaring afgegeven voor nelsen op fri [url=http://handtasonlinekopen.com/handtasonlinekopen.com]handtasonlinekopen.com[/url] erialen te verspreiden .burgemeester juli锟斤拷n castro lanceerde de inaugurele college week in san antoni [i]http://kledingpolo.com/Ralph Lauren Hoed[/i] ley punter ethan perry vastbesloten om tcu , rangers coach larry hill said.perry was een tweede team a [i]http://handtasonlinekopen.com/Michael Kors Portemonnee Handtassen[/i] mstige bruidegom afgestudeerd aan pawling high school in 2001.an oktober bruiloft is gepland .de esper [u][url=http://kledingpolo.com/kledingpolo.com]kledingpolo.com[/url][/u]

    Reply
  • NMfemiumiunegozi.com/Prada Portafogli Outlet 65

    Posted by al0q8m52oc on 07/12/2013 03:56am

    ha scritto il libro della serie 锟斤拷 cresciuto da , canta alcune canzoni pure. keyser gira racconti di og [i][url=http://www.negoziofranklinmarshall.com/Franklin marshall Hoodie]Franklin marshall Hoodie[/url][/i] cpria commedia schizzo , chiamato锟絋lui overtime comedy hour . / p 锟絋lui overtime comedy hour ? presenter [u][url=http://www.miumiunegozi.com/Prada Portafogli Outlet]Prada Portafogli Outlet[/url][/u] detto .锟斤拷t 'solo un incidente in un brutto posto in un brutto momento , ? una dispatcher ha detto la pol [i]http://www.negoziofranklinmarshall.com/donna Franklin Marshall pantaloni[/i] itecture di san antonio al pearl , 200 e. grayson st., suite 110.saenz , sociologo e demografo sociale , [b]http://www.miumiunegozi.com/www.miumiunegozi.com[/b]

    Reply
  • edhardyhinta.com/ED Hardy Naiset High Top nhkow28

    Posted by SU6n9o45vg on 07/11/2013 10:12pm

    next meal. More than pretty, it's also practical. Click on a photo and it links to the site that first posted the recipe. It's that easy.On Father's Day, I turned to my 锟斤拷Summer Grilling锟斤拷 board and went with a barbecue corn with Mexican spicy butter and lime recipe from Eat Drink Daily (now eatdrinkpaleo) that was very spicy. And very good. Also on the menu: a mustard chicken recipe from seriouseats that I had pinned onto 锟斤拷Food is LOVE-ly.锟斤拷 (Naming your boards is also part of the fun.)I sometimes browse pins for a new but easy twist to the tried and true. I usually roast Br [b]http://edhardyhinta.com/Ed hardy huppari[/b] your minimum distribution (and pay taxes on it) before the conversion can take place. Ordinarily, RMDs must be taken by Dec. 31 to avoid the penalty. However, if it's your first distribution you may wait until April 1 the year after turning 70 ?. 锟斤拷 Use the Uniform Lifetime Table if your spouse isn't more than 10 years younger than you, your spouse isn't the sole beneficiary, or you're single. 锟斤拷 The Single Life Expectancy Table is for beneficiaries of accounts whose owner has died.Although you must calculate the RMD separately for each IRA you own, you may withdraw the combine [i]http://dcdanmarkonline.com/dcdanmarkonline.com[/i] f raccoons, mitigated the disappointment of not seeing a quetzal in the reserve. A trio near us did see the sought-after bird, but never mind: Pura vida.He's walked through fire, crashed a speeding car and thrown countless punches. Such high-risk behavior is all in a day's work for Eddie J. Fernandez.The veteran stunt performer and actor 锟斤拷 he prefers the term 锟斤拷action actor锟斤拷 over 锟斤拷stuntman锟斤拷 锟斤拷 has his work featured in two films in theaters this month. He's the stunt double for Diego Luna in the heist thriller 锟斤拷Contraband,锟斤拷 and he has a small 锟斤拷 though action-filled 锟斤拷 pa [url=http://dcdanmarkonline.com/dc sko]dc sko[/url] ing, impaired judgment, impulsivity, and distractibility. This same enzyme produces a reduction in memory-related cell firing, the mechanism for short-term memory. Long-term stress can change the structure of the brain as well as decrease the size of the hippocampus, which is also critical for memory and mood.This can have a big impact on both academic learning and the ability to keep appointments and meet deadlines. Students with these difficulties may not understand what is required of them. Difficulties with organization are likely to adversely affect time management and pla [u]hthttp://edhardyhinta.com/ED Hardy Naiset High Top[/u]

    Reply
  • zr9j3m9p94k

    Posted by 7f35auh1gm on 07/10/2013 05:16am

    dksfy78Nike Free deutschland nike schuhe free run polo ralph lauren jacken nike free günstig nike free schuhe xkmlg36nike free 5.0 schwarz herren Nike free ralph lauren für kids ralph lauren mode ralph lauren daunenjacke oluuu77nike free schwarz herren ralph lauren pulli ralph lauren ralph parfum Nike free ralph lauren übergröße wrbqm23nike schuhe free run 5.0 cap ralph lauren ralph lauren polo hemd ralph lauren daunenjacke ralph lauren polo jacke ndyyy74Nike Free Run nike run free nike free 5.0 v4 ralph lauren für kids ralph lauren pulli trzsv60polo ralph lauren damen ralph lauren günstig ralph lauren pulli nike free run damen kindermode ralph lauren fbbuc16nike free preis ralph lauren sonnenbrillen ralph lauren günstig nike free schwarz nike free run damen odumv92nike schuhe free run polo ralph lauren damen nike free manner nike free billig kaufen ralph lauren übergröße lyvub52cap ralph lauren ralph lauren ralph parfum nike 3.0 free nike free run 3.0 herren blusen ralph lauren vwywx45nike free preis kindermode ralph lauren ralph lauren polo jacke ralph lauren polo hemd ralph lauren handtaschen http://nikefree-5-0.webs.com

    Reply
  • sklepedhardyonline.com/Ed Hardy Polo Shirt rsjek54

    Posted by SW0v8x94jt on 07/08/2013 12:52am

    rych cv zawiera elf macy , umys?owego aide szpitala i czystsze mieszkanie - ?le trafi? w szkielety w jego w?as [b][url=http://fendiitaliaonline.com/fendiitaliaonline.com]fendiitaliaonline.com[/url][/b] ejmowa? r锟斤拷?ne tematy , w tym lotem b?yskawicy odzysku , stanowymi i federalnymi i polityki , i walki z klesz [url=http://sklepedhardyonline.com/锘縮klepedhardyonline.com]锘縮klepedhardyonline.com[/url] handlowe w sobot? od 10 rano do 3 pmthe imprezy odb?dzie si? w state farm kathleen banse zak?adu ubezpiecze锟斤拷 [u][url=http://fendiitaliaonline.com/fendiitaliaonline.com]fendiitaliaonline.com[/url][/u] i w du?ej mierze do bezpiecznej przystaniprawo , kt锟斤拷re chroni businesses.coming w wersji drukowanej dzis [u]http://sklepedhardyonline.com/Ed Hardy Damskie[/u]

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Wednesday, September 24, 2014 8:00 AM - 9:00 AM PDT According to a recent Forrester Research report, many companies are choosing low-code platforms over traditional programming platforms, due to the speed with which low-code apps can be assembled and tested. With customer-facing applications on the rise, traditional programming platforms simply can't keep up with the "short schedules and rapid change cycles" required to develop these applications. Check out this upcoming webinar and join Clay Richardson from …

  • Not long ago, security was viewed as one of the biggest obstacles to widespread adoption of cloud-based deployments for enterprise software solutions. However, the combination of advancing technology and an increasing variety of threats that companies must guard against is rapidly turning the tide. Cloud vendors typically offer a much higher level of data center and virtual system security than most organizations can or will build out on their own. Read this white paper to learn the five ways that cloud …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds