代码之家  ›  专栏  ›  技术社区  ›  Foxxed

ASP.net FindControl返回null

  •  0
  • Foxxed  · 技术社区  · 11 年前

    我有这样的代码

    protected void Button1_Click(object sender, EventArgs e)
    
    {
                Table t = new Table() ;
                t.ID = "T1";
                t.Visible = true;
                MyPanel.Controls.Add(t);
    }
    
    protected void Button2_Click(object sender, EventArgs e)
    
    {
                Table t = (Table)MyPanel.FindControl("T1");
    }
    

    我有问题: Table t = (Table)MyPanel.FindControl("T1");

    在变量t中,现在有对null的引用。我看起来应用程序不知道生成的代码背后的情况 桌子我是否必须将表“注册”到MyPanel以外的其他地方?谢谢你的回答。

    编辑 有关该问题的更多信息

    我有一个没有母版页的简单页面。有一个带数字的网格视图。这个数字意味着新的TAble将有多少行和单元格。当用户选择一行时,我想创建适当的表,点击第二个按钮后,我需要从表中收集信息。OnInit或PreRender我不知道,我需要多少行。这是否意味着我的问题在技术上是不可能的?

    3 回复  |  直到 11 年前
        1
  •  1
  •   Archlight    11 年前

    您有Panel1,但正在搜索一个名为MyPanel的表??

    protected void Button2_Click(object sender, EventArgs e)
    {
                Table t = (Table)Panel1.FindControl("T1");
    }
    

    这应该能让你坐到桌子上

    编辑

    好吧,我发现了一些旧的webForms的东西,它会让这件事变得很糟糕。

    但是,如果您想稍后在代码中与表交互,则必须在页面的initialize或preInit事件上添加表。你必须 再现 每个回邮的控制。

    public static Control FindControlRecursive(Control root, string id)
    {
        if (root.id == id)
            return root;
        foreach (Control ctrl in root.Controls)
        {
            Control FoundCtl = FindControlRecursive(ctrl, id);
           if (FoundCtl != null)
                return FoundCtl;
        }
        return null;
    }
    

    你可以像这样使用它。

    table myTable = FindControlRecursive(this.Master, "T1") as Table
    
        2
  •  0
  •   Ahmed Farouk    11 年前

    在PreRender上执行代码

    protected override void OnPreRender(EventArgs e)
        {
                Table t = new Table() ;
                t.ID = "T1";
                t.Visible = true;
                MyPanel.Controls.Add(t);
        }
    
        3
  •  -3
  •   Null29    7 年前

    ctl00$ContentPlaceHolder1$UrunlerAjax1$rptCustomers

    内容占位符-->用户控制-->中继器

    Repeater rptCustomers = this.Page.Master.FindControl("ContentPlaceHolder1").FindControl("UrunlerRAjax1").FindControl("rptCustomers") as Repeater;
    

    中继器rptCustomers=this.Page.Master.FindControl(“ContentPlaceHolder1”).FindControl(“UrunlerAjax1”)FindControl(”rptCustomers“)作为中继器;

    Repeater repeaterName=this.Page.Master.FindControl(“ContentName”).FindControl(“UsercontrolName”).FindControl((“repeaterName”)作为Repeater;