从静态方法发出修改控制

时间:2011-04-20 23:50:26

标签: c# asp.net

这里有几个相似的问题,但它们对我不起作用。

我在页面上有自定义下拉列表,页面名称为WebForm1。在WebForm1我有一个汇编引用:<%@ Register Assembly="GroupDropDownList" Namespace="GroupDropDownList" TagPrefix="cc1" %>

然后我有一个像这样的静态方法:

    public static void Populate_Country_DDL(System.Web.UI.Page page)
        {
            GroupDropDownList
                .GroupDropDownList ddlCountry =
 ((GroupDropDownList.GroupDropDownList)page.FindControl("ddlCountry"));

            using (DataContext db = new DataContext())
            {
                var country = db.Countries.OrderBy(x => x.Text);

                ddlCountry.DataSource = country; //Error here

WebForm1我试图访问静态方法,如下所示:

Utility.Populate_Country_DDL(this.Page);

问题是我得到一个“对象引用未设置为对象的实例”错误。我在我的实用程序类中为GroupDropDownList

添加了一个using语句

GroupDropDownList只允许我将选项组放在下拉列表中。

更新为了解决这个问题,我修改了我的实用工具方法,取了ContentPlaceHolder而不是Page类,然后在我的调用方法中,我找到了ContentPlaceHolder当前页面MasterPage是这样的:

Utility.Populate_Country_DDL(
                (ContentPlaceHolder)this.Master
                .FindControl("ContentPlaceHolder1"));

2 个答案:

答案 0 :(得分:2)

我认为问题在于找不到您正在查看页面的控件。你确定名字是否正确?

FindControl方法不会进入控件层次结构,因此您必须编写自己的方法来搜索页面上的所有控件。

E.g。递归版:

    public static Control FindControlRecursively(Control parent, string id)
    {
        Control control = parent.FindControl(id);

        if (control != null)
        {
            return control;
        }
        else
        {
            foreach (Control childControl in parent.Controls)
            {
                control = FindControlRecursively(childControl, id);
                if (control != null)
                {
                    return control;
                }
            }
        }

        return null;
    }

或没有递归的版本:

    public static Control DeepFindControl(Control parent, string id)
    {
        Queue<Control> queue = new Queue<Control>();

        queue.Enqueue(parent);

        while (queue.Count > 0)
        {
            Control currentParent = queue.Dequeue();

            Control control = currentParent.FindControl(id);

            if (control != null)
            {
                return control;
            }

            foreach (Control childControl in parent.Controls)
            {
                queue.Enqueue(childControl);
            }
        }

        return null;
    }

答案 1 :(得分:2)

来自MSDN

  

可以使用FindControl方法   访问ID不是的控件   在设计时可用。方法   仅搜索页面的直接,或   顶级容器; 它没有   以递归方式搜索控件   命名容器包含在   页。访问控件   从属命名容器,调用   该容器的FindControl方法。

您只能在要查找的控件的直接父级上使用FindControl(),否则它将返回null