Create an
Array of Server controls dynamically and capture their events. cbxYesArray[i].ID = "cbxY" + i;
Adding Controls Dynamically
Controls can
belong to a collection of that particular control. This collection is stored as
an array.
CheckBox[]
cbxYesArray = new CheckBox[3];
cbxYesArray[0]
= new CheckBox();
cbxYesArray[0].Text = "YES";
Because arrays
must be initialized, the number of controls must be determined before use
(typically
Page_Load) so that
the array can be initialized to that number.
cbxYesArray =
new CheckBox[iControlCount];
Controls that are
added dynamically must belong to the page or a container control. Container
controls
Include tables,
panels, datagrids, etc.
tdControls.Controls.Add(cbxYesArray[i]);
Once executed the
ASP.NET page is removed from memory. Because of this the dynamic controls MUST
BE recreated on
each PostBack is the control is to be maintained on the page. Typically this
occurs in the
Page_Load event
which will fire before other events.
Adding the Events
When a Yes box is checked,
change the Text to Green and reset the No box if it is checked. When a No box is
checked, change the Text to Red and reset the Yes box if it is checked. If an
entry is un-checked, reset the Text to black.
Two conditions must be met in
order to capture the events:
1. The control(s)
must be re-initialized in the page before the event processing can occur.
2. Because the
control is not available during design, a separate event (method) must be
created to handle to event(s) in question. That method is associated with the
control when it is created.
i. VB uses the AddHandler statement
ii
C# assigns the
event with the EventHandler method
cbxYesArray[i].AutoPostBack = true;
cbxYesArray[i].CheckedChanged += new EventHandler(CheckBoxClick);
By default, the CheckBox control
does not automatically post the form to the server when it is clicked. To enable
automatic posting, set the AutoPostBack property to true.
By using the ID property, you
can store the position of the control in the array:
Creating Dynamic Server Controls and Associate Events.
0 comments
Hide comments