.FindControl始终返回null [英] .FindControl always returns null

查看:387
本文介绍了.FindControl始终返回null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两种方法。首先创建一个表动态地,我补充一点,表成的占位符。

I have two methods. The first creates one table dynamicly, and I add that table into a PlaceHolder.

private void generateData(){
    Table tbl = new Table();
    tbl.ID = "table1";
    holder_info.Controls.Add(tbl);
    //....adding tr's and td's....
    //....adding CheckBox in tds....
}

如果我做.FindControl(...)这个方法里面,我可以找到控制unsing:

If I do .FindControl("...") inside this method I can find the control unsing:

CheckBox check = (CheckBox)holder_info.FindControl("checkbox1");



这是确定的,但不是我假装。

It's OK, but not what I pretend.

在第二个方法,我要检查用户是否选中的复选框,并做了一些东西,但我无法找到控制(它总是返回null)。

In the second method, I want to check whether the user checked checkBox and did something, but I can't find the control (it always returns null).

protected void saveInfo_Click(object sender, ImageClickEventArgs e)
{
  CheckBox check = (CheckBox)holder_info.FindControl("checkbox1");
  if(check.checked){ ... }
}



另外,如果我试图找到控制表1,我得到空。

Also, if I try to find the control "table1", I get null.

为什么会出现这种情况?

Why does this happen?

推荐答案

那是因为你要添加的控制动态页面,当你点击该按钮页面上得到一个回传并删除动态添加控件。这就是为什么它不是能够找到按钮单击事件CheckBox控件

It's because you are adding a control dynamically to page, and when you click on the button page get a postback and remove the dynamically added controls. That is why it's not able to find the checkbox control in the button click event.

有关动态控件,请查看文章的保持状态。动态创建的控件ASP.NET应用程序中 的(代码项目)。

For dynamic controls, check the article Retaining State for Dynamically Created Controls in ASP.NET applications (The Code Project).

这篇关于.FindControl始终返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆