Thursday, January 17, 2013

There are practical reasons to bundle web forms controls together when creating them dynamically in a code behind file.

Refactoring the work I begun here I have learned that if one wants to have n number of controls for each record out of a database such as, for example...

  1. a checkbox for whether to delete a row
  2. a form field for editing a data point on the row
  3. a hidden form field to keep the integer id of the row

 
 

...that when creating web forms controls dynamically it is tricky to associate the n controls. I got around this by creating a new Panel for each set of three as seen here:

foreach (KeyValuePair<int,string> keyValuePair in subdomains)
{
   TextBox textBox = new TextBox();
   textBox.Attributes.Add("style", "float: left; width: 350px; margin-top: 4px;");
   textBox.Text = keyValuePair.Value;
   CheckBox checkBox = new CheckBox();
   checkBox.Attributes.Add("style", "float: left; margin: 6px 0px 0px 10px;");
   HiddenField hiddenField = new HiddenField();
   hiddenField.Value = keyValuePair.Key.ToString();
   Panel innerPanel = new Panel();
   innerPanel.Controls.Add(checkBox);
   innerPanel.Controls.Add(textBox);
   innerPanel.Controls.Add(hiddenField);
   LeftPanel.Controls.Add(innerPanel);
}

 
 

I then get a collection of panels back when its time to analyze stuff in the controls. From any one item in the collection, it isn't too tough to associate its three children together.

List<Panel> panels = new List<Panel>();
foreach (Panel panel in LeftPanel.Controls) panels.Add(panel);
foreach (Panel panel in panels)
{
   List<Control> controls = new List<Control>();
   foreach (Control control in panel.Controls) controls.Add(control);
   Tuple<bool, string, int> changeSet = new Tuple<bool, string, int>(((CheckBox)
         controls[0]).Checked, ((TextBox) controls[1]).Text,
         Convert.ToInt32(((HiddenField)controls[2]).Value));
}

No comments:

Post a Comment