关于动态控件添加的问题
我想做个在线测试,需要随机出题,所以要动态的添加n多控件 ,但是在.net2.0里面动态添加的控件,postback 后都消失了,不知道怎么办啊。代码如下
protected void btnRandom_Click(object sender, EventArgs e)
{
DataSet ds = testBLL.Test(Convert.ToInt32(this.tbNumber.Text), "");
this.pSelect.Visible = false;
pTest.Visible = true;
for (int loop = 0; loop < ds.Tables[0].Rows.Count; loop++ )
{
buildTest(ds.Tables[0].Rows[loop],loop);
}
this.pTest.Controls.Add(btnFinish);
}
protected void buildTest(DataRow dr, int loop)
{
David.Nephropathy.Model.test testData = new David.Nephropathy.Model.test();
testData.id = Convert.ToInt32(dr["id"]);
testData.title = dr["title"].ToString();
testData.type = dr["type"].ToString();
testData.answer = dr["answer"].ToString();
testData.A = dr["A"].ToString();
testData.B = dr["B"].ToString();
testData.C = dr["C"].ToString();
testData.D = dr["D"].ToString();
testData.E = dr["E"].ToString();
testData.F = dr["F"].ToString();
Label lbl = new Label();
lbl.ID = "t_" + testData.type + "_" + testData.id.ToString();
Literal ltTitle = new Literal();
ltTitle.Text = (loop + 1).ToString() + " . " + testData.title + "<br>";
lbl.Controls.Add(ltTitle);
switch (testData.type)
{
case "单选题":
RadioButtonList rbl = new RadioButtonList();
if (testData.A != string.Empty)
rbl.Items.Add(new ListItem("A:" + testData.A, "A"));
if (testData.B != string.Empty)
rbl.Items.Add(new ListItem("B:" + testData.B, "B"));
if (testData.C != string.Empty)
rbl.Items.Add(new ListItem("C:" + testData.C, "C"));
if (testData.D != string.Empty)
rbl.Items.Add(new ListItem("D:" + testData.D, "D"));
if (testData.E != string.Empty)
rbl.Items.Add(new ListItem("E:" + testData.E, "E"));
if (testData.F != string.Empty)
rbl.Items.Add(new ListItem("F:" + testData.F, "F"));
lbl.Controls.Add(rbl);
break;
case "多选题":
CheckBoxList cbl = new CheckBoxList();
if (testData.A != string.Empty)
cbl.Items.Add(new ListItem("A:" + testData.A, "A"));
if (testData.B != string.Empty)
cbl.Items.Add(new ListItem("B:" + testData.B, "B"));
if (testData.C != string.Empty)
cbl.Items.Add(new ListItem("C:" + testData.C, "C"));
if (testData.D != string.Empty)
cbl.Items.Add(new ListItem("D:" + testData.D, "D"));
if (testData.E != string.Empty)
cbl.Items.Add(new ListItem("E:" + testData.E, "E"));
if (testData.F != string.Empty)
cbl.Items.Add(new ListItem("F:" + testData.F, "F"));
lbl.Controls.Add(cbl);
break;
case "简答题":
case "问答题":
TextBox tb = new TextBox();
tb.Height = Unit.Pixel(50);
tb.Width = Unit.Pixel(500);
lbl.Controls.Add(tb);
break;
}
Literal ltAnswer = new Literal();
ltAnswer.ID = "answer" + testData.id.ToString();
ltAnswer.Text = testData.answer;
ltAnswer.Visible = false;
lbl.Controls.Add(ltAnswer);
this.pTest.Controls.Add(lbl);
}