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">
      <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>

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;

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)

   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.

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.


  • Jacobs Purses 65

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

    nuove informazioni verranno aggiunte e commenti sono benvenuti attraverso i link sul [u][/u] no nel fbs e per fcs scuole del texas .dopo il breve discorso di annullare il re guglielmo parade (sopra [i][url= 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] Italia[/u] trict 25 - 5a.nathan thompsonmacarthur , juniorsize : 6-5 , 260te : jace amaromacarthur , seniorsize : 6 [i] jacobs saldi[/i]

  • 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]æ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= 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= 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][/b]

  • 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= 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] 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= 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] Marc Jacobs Bolsas[/u]

  • 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

  • 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

  • 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=][/url] erialen te verspreiden .burgemeester juli锟斤拷n castro lanceerde de inaugurele college week in san antoni [i] Lauren Hoed[/i] ley punter ethan perry vastbesloten om tcu , rangers coach larry hill said.perry was een tweede team a [i] Kors Portemonnee Handtassen[/i] mstige bruidegom afgestudeerd aan pawling high school in oktober bruiloft is gepland .de esper [u][url=][/url][/u]

  • 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= marshall Hoodie]Franklin marshall Hoodie[/url][/i] cpria commedia schizzo , chiamato锟絋lui overtime comedy hour . / p 锟絋lui overtime comedy hour ? presenter [u][url= 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] Franklin Marshall pantaloni[/i] itecture di san antonio al pearl , 200 e. grayson st., suite 110.saenz , sociologo e demografo sociale , [b][/b]

  • 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] 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][/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= 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]ht Hardy Naiset High Top[/u]

  • 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

  • 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=][/url][/b] ejmowa? r锟斤拷?ne tematy , w tym lotem b?yskawicy odzysku , stanowymi i federalnymi i polityki , i walki z klesz [url=锘縮]锘縮[/url] handlowe w sobot? od 10 rano do 3 pmthe imprezy odb?dzie si? w state farm kathleen banse zak?adu ubezpiecze锟斤拷 [u][url=][/url][/u] i w du?ej mierze do bezpiecznej przystaniprawo , kt锟斤拷re chroni businesses.coming w wersji drukowanej dzis [u] Hardy Damskie[/u]

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

Top White Papers and Webcasts

  • As all sorts of data becomes available for storage, analysis and retrieval - so called 'Big Data' - there are potentially huge benefits, but equally huge challenges...
  • The agile organization needs knowledge to act on, quickly and effectively. Though many organizations are clamouring for "Big Data", not nearly as many know what to do with it...
  • Cloud-based integration solutions can be confusing. Adding to the confusion are the multiple ways IT departments can deliver such integration...

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date