LiteralControl问题的范围

时间:2011-06-07 08:36:14

标签: c# asp.net controls scope

我有一段代码,使用2个while循环创建动态控件。 正如您所看到的,我被迫在每个循环中声明两个LiteralControl,因为如果我不这样做,puBugList.Controls.Add(lineBreak)将不会确认。

问:为什么我不能在while循环中看到控件的范围?

    //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);
    }

1 个答案:

答案 0 :(得分:1)

我认为你的问题是,如果你在while循环之外实例化LiteralControl,那么你在整个代码中实际使用相同的对象,并且你不能将同一个控件两次添加到Controls集合中另一个控制。

尝试以下方法:

 LiteralControl lineBreak = null;
 (...)

 while (repReader.Read())
 {
      literalControl = new LiteralContro(...);
 }

无论如何,除非你在while循环之外的范围内需要lineBreak,否则在循环中声明变量没有错,所以你的代码完全正常。