【问题标题】:Finding control on SharePoint page在 SharePoint 页面上查找控件
【发布时间】:2011-10-26 21:11:13
【问题描述】:

我试图找到位于我的 SharePoint 页面上的 SPDataSource 控件。我发现下面的代码可能工作正常,我只是不知道要传递什么。

public static Control FindControlRecursive(Control Root, string Id)
{
    if (Root.ID == Id)
        return Root;

    foreach (Control Ctl in Root.Controls)
    {
        Control FoundCtl = FindControlRecursive(Ctl, Id);

        if (FoundCtl != null)
            return FoundCtl;
    }

    return null;
}

我不知道如何让它搜索整个页面或至少搜索控件所在的 ContentPlaceHolder。

编辑

看起来我在这里有一个更基本的问题。不知道如何解释,但在运行我的代码之前我没有打开页面。我通过以下方式打开网站:

using (SPWeb web = thisSite.Site.OpenWeb("/siteurl/,true))

所以当我尝试查找下面的页面时,我发现对象引用未设置为对象实例。

var page = HttpContext.Current.Handler as Page;

也许我走错了路,我在这里还处于婴儿期,所以我只是在想办法解决问题!

【问题讨论】:

  • 请解释一下您为什么尝试通过代码查找 SPDataSource?
  • 我有一个用于从模板创建站点的列表的事件处理程序,现在我希望它使用从列表项带来的数据更新模板站点上的 SPDataSource。主要是,我希望更新 SPDataSource 中的 SelectCommand,以便过滤数据。

标签: sharepoint sharepoint-2007


【解决方案1】:

你得到的实际上不是 SharePoint 特定的,它是 c# asp.net。

不管怎样,你可以这样称呼它

var page = HttpContext.Current.Handler as Page;
var control = page; // or put the element you know exist that omit (is a parent) of the element you want to find
var myElement = FindControlRecursive(control, "yourelement");

您很可能还需要投射回报

var myElement = (TextBox)FindControlRecursive(control, "yourelement");
// or
var myElement = FindControlRecursive(control, "yourelement") as TextBox;

但是有更有效的方法来编写这样的方法,这里是一个简单的例子

public static Control FindControlRecursive(string id)
{
    var page = HttpContext.Current.Handler as Page;
    return FindControlRecursive(page, id);
}

public static Control FindControlRecursive(Control root, string id)
{
    return root.ID == id ? root : (from Control c in root.Controls select FindControlRecursive(c, id)).FirstOrDefault(t => t != null);
}

按照我之前建议的方式调用它。

如果您正在处理较大的页面,上述方法可能会有点慢,您应该做的是针对使用泛型的方法。它们比传统方法快得多。

试试这个

public static T FindControlRecursive<T>(Control control, string controlID) where T : Control
{
    // Find the control.
    if (control != null)
    {
        Control foundControl = control.FindControl(controlID);
        if (foundControl != null)
        {
            // Return the Control
            return foundControl as T;
        }
        // Continue the search
        foreach (Control c in control.Controls)
        {
            foundControl = FindControlRecursive<T>(c, controlID);
            if (foundControl != null)
            {
                // Return the Control
                return foundControl as T;
            }
        }
    }
    return null;
}

你这样称呼它

var mytextBox = FindControlRecursive<TextBox>(Page, "mytextBox");

【讨论】:

  • 编辑了我的帖子,认为我有一个更大的问题阻止我尝试您的代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-31
  • 2011-04-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多