将数据从代码隐藏文件动态加载到中继器中
本文关键字:加载 中继器 动态 隐藏文件 数据 代码 | 更新日期: 2023-09-27 17:59:44
问题可能有点长:
我正在制作一个在线评估门户网站,数据库中有不同类型的问题,需要以网络形式加载。问题可以是单答案(单选按钮)或多答案(复选框按钮)。因此,根据类型,我根据需要创建单选按钮或复选框,并在运行时将其加载到Repeater中。代码如下:
SqlCommand cmd = new SqlCommand("select * from tbl_QuestionAnswer", con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
if ((string)dr["type"] == "SingleAnswer")
{
RadioButton rAnswer1 = new RadioButton();
rAnswer1.ID = "rbl_Answer1";
rAnswer1.GroupName = "QAnswer1";
rAnswer1.Text = dr["Answer1"].ToString();
Panel PAnswer1 = e.Item.FindControl("PAnswer1") as Panel;
PAnswer1.Controls.Add(rAnswer1);
RadioButton rAnswer2 = new RadioButton();
rAnswer2.ID = "rbl_Answer2";
rAnswer2.GroupName = "QAnswer1";
rAnswer2.Text = dr["Answer2"].ToString();
Panel PAnswer2 = e.Item.FindControl("PAnswer2") as Panel;
PAnswer2.Controls.Add(rAnswer2);
RadioButton rAnswer3 = new RadioButton();
rAnswer3.ID = "rbl_Answer3";
rAnswer3.GroupName = "QAnswer1";
rAnswer3.Text = dr["Answer3"].ToString();
Panel PAnswer3 = e.Item.FindControl("PAnswer3") as Panel;
PAnswer3.Controls.Add(rAnswer3);
RadioButton rAnswer4 = new RadioButton();
rAnswer4.ID = "rbl_Answer4";
rAnswer4.GroupName = "QAnswer1";
rAnswer4.Text = dr["Answer4"].ToString();
Panel PAnswer4 = e.Item.FindControl("PAnswer4") as Panel;
PAnswer4.Controls.Add(rAnswer4);
}
else
{
CheckBox cAnswer1 = new CheckBox();
cAnswer1.ID = "chk_Answer1";
cAnswer1.Text = dr["Answer1"].ToString();
Panel PAnswer1 = e.Item.FindControl("PAnswer1") as Panel;
PAnswer1.Controls.Add(cAnswer1);
CheckBox cAnswer2 = new CheckBox();
cAnswer2.ID = "chk_Answer2";
cAnswer2.Text = dr["Answer2"].ToString();
Panel PAnswer2 = e.Item.FindControl("PAnswer2") as Panel;
PAnswer2.Controls.Add(cAnswer2);
CheckBox cAnswer3 = new CheckBox();
cAnswer3.ID = "chk_Answer3";
cAnswer3.Text = dr["Answer3"].ToString();
Panel PAnswer3 = e.Item.FindControl("PAnswer3") as Panel;
PAnswer3.Controls.Add(cAnswer3);
CheckBox cAnswer4 = new CheckBox();
cAnswer4.ID = "chk_Answer4";
cAnswer4.Text = dr["Answer4"].ToString();
Panel PAnswer4 = e.Item.FindControl("PAnswer4") as Panel;
PAnswer4.Controls.Add(cAnswer4);
}
}
但这里的问题是所有的答案都包含在所有的问题中。即从dr["Answer1"]获取"Answer1"列中的所有数据,然后制作复选框或单选按钮。我不知道为什么会发生这种情况,因为它应该一次只处理一行,并且只处理该行的数据。
同样,这在两个问题之前运行良好。之后,如果我添加第三个问题并尝试加载它,它会出现错误,说"找到了多个ID为'rbl_Answer1'的控件。FindControl要求控件具有唯一的ID。"。这也是正确的。因此,我需要一种方法来将问题动态加载到web表单中,这取决于单个答案或多个asnwer
很明显,如果查询中有多行,则可以创建具有相同id的控件。
尝试进行动态字段/控制,并为那些控制设置动态ID
while (dr.Read())
{
if ((string)dr["type"] == "SingleAnswer")
{
RadioButton rAnswer1 = new RadioButton();
rAnswer1.ID = "rbl_Answer" + dr["AnswerID1"].ToString();
或者类似的东西。。。