c# - ASP.NET How to access multiple form labels text property with foreach loop -


i have form runat= "server" id = "myform" . profile page lots of labels. getting input text sql database. if sql data base have null value, wish text changed "not specified". such reason using following code, not working.

foreach (control item in myform.controls) {     label lbl = null;     bool labelisempty = false;     try     {         lbl = (label)item;         labelisempty = (lbl.text == string.empty && lbl != null);     }     catch      {     }      if (labelisempty)     {         lbl.text = "not specified";     } } 

myform.controls gives collection contains controls withing container( not labels). have check type control while iterating collection in order avoid throwing exception. in additional comment ware specify label has default text "label" need include in condition. whole scenario can implemented following:

      foreach (control  item in myform.controls)         {             if (item label)             {               var  lbl = (label)item;               bool labelisempty = false;               try               {                   lbl = (label)item;                   labelisempty = (lbl != null && lbl.text == string.empty && lbll.text!="label");               }               catch                {                //throw error message               }               if (labelisempty)               {                   lbl.text = "not specified";               }             }         } 

note :-

you need reorder conditions avoid exception. check string.empty should comes after check control null. because and not check second condition if first 1 false, lbl.text throw nullreferenceexception if lbl null


Comments

Popular posts from this blog

c# - How Configure Devart dotConnect for SQLite Code First? -

java - Copying object fields -

c++ - Clear the memory after returning a vector in a function -