1

I need to store data from a form for recovery from the session. Below is my rough first attempt for a generalized method for textboxes:

Load Session:

Dictionary<string, string> AppInfo = (Dictionary<string,string>) Session["ApplicantionInfo"];
this.Controls.OfType<TextBox>()
         .ToList<TextBox>()
         .ForEach( x => x.Text = AppInfo[x.ID] );

Save Session:

Session["ApplicationInfo"] = this.Controls.OfType<TextBox>()
                                  .ToList<TextBox>()
                                  .ToDictionary<TextBox,string>(kvp => kvp.ID);  

However, it appears that the Controls collection is not working for me. What am I doing wrong?

this.Controls.OfType<TextBox>() yields no results at run time when I do a quick watch on it.

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Joshua Enfield
  • 17,642
  • 10
  • 51
  • 98

3 Answers3

3

See Recursive control search with Linq.

Community
  • 1
  • 1
mellamokb
  • 56,094
  • 12
  • 110
  • 136
1

This is how I access form controls.

for (int i = 0; i < this.Controls.Count; i++)
{
      this.Controls[i].Visible = false;

 }
clamchoda
  • 4,411
  • 2
  • 36
  • 74
1

How about

public static List<Control> GetAllControls(List<Control> controls, Type t, Control parent)
{
            foreach (Control c in parent.Controls)
            {
                if (c.GetType()== t)
                    controls.Add(c);
                if (c.HasControls())
                    controls = GetAllControls(controls, t, c);
            }
            return controls;
}

and call

var allControls = new List<Control>();
GetAllControls(allControls, typeof(TextBox), Page);
Bala R
  • 107,317
  • 23
  • 199
  • 210