Reputation: 45
Based on the data being returned from a database, a number of textboxes and checkboxes are dynamically added to my page using the following code:
int counter = 0;
foreach (DataRow dr in dsData.Tables[0].Rows){
CheckBox chk_valid = new CheckBox();
chk_valid.Enabled = true;
chk_valid.ID = "dynamicchk" + counter.ToString();
TextBox txt_task = new TextBox();
txt_task.Enabled = true;
txt_task.Text = dr[0].ToString();
txt_task.Width = 300;
txt_task.TextMode = TextBoxMode.MultiLine;
txt_task.ID = "dynamictask" + counter.ToString();
TextBox txt_id = new TextBox();
txt_id.Enabled = true;
txt_id.Text = "ID.";
txt_id.Width = 90;
txt_id.ID = "dynamicid" + counter.ToString();
TextBox txt_email = new TextBox();
txt_email.Enabled = true;
txt_email.Text = "E-mail Address";
txt_email.Width = 150;
txt_email.ID = "dynamicemail" + counter.ToString();
dynamic_controls_holder.Controls.Add(chk_valid);
dynamic_controls_holder.Controls.Add(new LiteralControl(" "));
dynamic_controls_holder.Controls.Add(txt_task);
dynamic_controls_holder.Controls.Add(new LiteralControl(" "));
dynamic_controls_holder.Controls.Add(txt_id);
dynamic_controls_holder.Controls.Add(new LiteralControl(" "));
dynamic_controls_holder.Controls.Add(txt_email);
dynamic_controls_holder.Controls.Add(new LiteralControl("<br /><br />"));
counter += 1;
}
Now, I also need to dynamically add calendar controls (there should be a button in front of the textbox and checkbox in each row; and on clicking that button, a calendar should be displayed. On selecting a date from the calendar, the textbox value should be changed to the date selected.)
Normally, this would've been easy if I were to use jQuery UI but my limitation is that in the environment I work in, I cannot use jQuery UI or any other ajax calendar. I have to use asp:calendar.
Upvotes: 0
Views: 1316
Reputation: 11903
To answer your question, you should design the calendar, textbox, button etc functionality inside a user control. Then in your loop, you just add that control into your dynamic controls with a simple LoadControl("~/MyControl.ascx") call.
To go one step further, you should consider using the asp:Repeater control. It does everything that you are doing manually right now: looping through data and creating dynamic controls. It would take less effort to do that since you could actually design the rows as a template with the ASPX designer, instead of writing lots of code.
Upvotes: 1