Hi!
I'm trying to create a page with dynamic controls, and I'm having difficulty wrt the liffe cycle.
The page has some static controls, but also a table which has dynamic rows, cells of which contain dynamic controls, including a DropDownList.
The idea is that the page has an "Add" button, which should result in a new row being added to the table. The selected values in the earlier DropDownLists must be preserved.
So, first time the page looks like:
[Static Controls]
[TableRow1 [DropDownList1]]
[Add Button]
Clicking the button should result in:
[Static Controls]
[TableRow1 [DropDownList1]]
[TableRow2 [DropDownList2]]
[Add Button]
with DropDownList1 selection being preserved.
The Button click event code tries to read the current selections of the DDLs and store them in session, It then causes a redirect to the same page, forcing the page to be drawn as new (from the life cycle point of view).
My sequence of code is:
protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack) {
populate();
}
populateVolatile();
}
where populate() sets up the static controls with data retrieved from a database (first time) or session (subsequently), and
populateVolatile() creates and fills the dynamic controls depending on the session data, including DDL selections.
It contains the code:
// add each type/num info to table
foreach (TypeNumInfo tni in volInfo.typeNumRows) {
TableRow tr = new TableRow();
// index number
TableCell tc1 = new TableCell();
tc1.Text = tni.idx.ToString();
tr.Cells.Add(tc1);
// add a DDL
TableCell tc2 = new TableCell();
DropDownList ddl = new DropDownList();
// add ID and list data
ddl.ID = "ddl" + tni.idx;
foreach (ListItem li in dTypes) {
ddl.Items.Add(li);
}
// set the selected
// TODO not working
ddl.SelectedIndex = tni.typeSel;
tc2.Controls.Add(ddl);
tr.Cells.Add(tc2);
tblTypeNum.Rows.Add(tr);
}
The button click code is as follows:
protected void bAddTypeNum_Click(object sender, EventArgs e) {
// get dept, applies selections from static controls
statInfo.selDept = ddlDept.SelectedIndex;
statInfo.selApplies = ddlApplies.SelectedIndex;
// create new type/num info representing tablerow data
TypeNumInfo tni = new TypeNumInfo();
int lastIdx = volInfo.typeNumRows.Count;
tni.idx = lastIdx + 1;
// add to list
volInfo.typeNumRows.Add(tni);
// cache previous rows
int i = 0;
foreach (TableRow tr in tblTypeNum.Rows) {
// if row has droplist, i.e. more than 1 cell
if (tr.Cells.Count > 1) {
DropDownList ddl = (DropDownList)tr.Cells[1].Controls[0];
// get the selection in that row
// TODO not working reliably
volInfo.typeNumRows[i++].typeSel = ddl.SelectedIndex;
}
}
// update session
Session[strStat] = statInfo;
Session[strVol] = volInfo;
// draw as new page
Response.Redirect("");
}
I know the redirect creates an extra trip to the server, but I couldn't find a useful way to enable redrawing after the button event.
Everything works fine except for the DDL selection handling - I cannot set or correctly read the selections.
Help!
John