I have a piece of code that creates dynamic controls using 2 while loops.
As you can see, I am forced to declare both LiteralControls INSIDE each while loop because if I don’t, the puBugList.Controls.Add(lineBreak) will not acknowledge.
Q: Why can I not see the scope of the controls from inside a while loop?
//this control is not acknowledged
//LiteralControl lineBreak = new LiteralControl("<br/>");
while (nwReader.Read())
{
int id = (int)nwReader["bid"];
string user = (string)nwReader["buname"];
string prob = (string)nwReader["bproblem"];
string content = id + ". " + user + ": " + prob + "<br/>";
Label lb = new Label();
lb.Text = content;
phBugList.Controls.Add(lb);
//forced to declare 1 here
LiteralControl lineBreak = new LiteralControl("<br/>");
String sqlSelRep = "SELECT * FROM [reply] WHERE bid=@bid";
SqlCommand cmdSelRep = new SqlCommand(sqlSelRep, conn);
cmdSelRep.Parameters.AddWithValue("@bid", id);
SqlDataReader repReader = cmdSelRep.ExecuteReader();
while (repReader.Read())
{
//forced to declare another
LiteralControl lineBreak2 = new LiteralControl("<br/>");one here
string msg = (string)repReader["rmsg"];
Label lbRep = new Label();
lbRep.Text = "Admin: \"" + msg + "\"";
phBugList.Controls.Add(lbRep);
phBugList.Controls.Add(lineBreak2);
}
repReader.Close();
if (Convert.ToInt32(Session["user"]) == 1)
{
phBugList.Controls.Add(lineBreak);
TextBox tbRep = new TextBox();
tbRep.ID = "tb" + id.ToString();
phBugList.Controls.Add(tbRep);
LinkButton butRep = new LinkButton();
butRep.ID = "rep" + id.ToString();
butRep.Text = " Reply";
butRep.Click += InsertReply;
phBugList.Controls.Add(butRep);
LinkButton butDel = new LinkButton();
butDel.ID = "del" + id.ToString();
butDel.Text = " Delete";
butDel.Click += DeleteBug;
phBugList.Controls.Add(butDel);
phBugList.Controls.Add(lineBreak);
}
phBugList.Controls.Add(lineBreak);
}
I think you’r problem is that if you instantiate
LiteralControloutside the while loop you are effectively using the same object throughout your code, and you cannot add the same control twice to aControlscollection of another control.Try the following:
Anyway, unless you need
lineBreakin scope outside the while loop there is nothing wrong declaring the variable inside the loop so your code is perfectly fine.