从代码后面引用XSL模板中的控件?

时间:2010-04-06 12:05:14

标签: sharepoint

我有一个自定义的NewItem.aspx,我是通过从现有的创建一个新的aspx来创建的

我想在XSL模板中连续放置一个控件,如下所示

<asp:DropDownList ID="ddlSectors" AutoPostBack="true" runat="server" __designer:bind="{ddwrt:DataBind('i',ddlSectors,'SelectedValue','TextChanged','ID',ddwrt:EscapeDelims(string(@ID)),'@Sector')}">
                    </asp:DropDownList>
                        <!--<SharePoint:FormField runat="server" id="ff7{$Pos}" ControlMode="New" FieldName="Sector" __designer:bind="{ddwrt:DataBind('i',concat('ff7',$Pos),'Value','ValueChanged','ID',ddwrt:EscapeDelims(string(@ID)),'@Sector')}"/>-->
                        <SharePoint:FieldDescription runat="server" id="ff7description{$Pos}" FieldName="Sector" ControlMode="New"/>

现在我想从我的代码库中引用ddlSectors,但它总是抛出一个未设置为对象instatnce的对象引用。

我相信这是因为控件在XSL模板中。

那么有没有解决方法?

感谢

2 个答案:

答案 0 :(得分:0)

问题:每行都显示下拉列表吗?

但您可以尝试引用父控件并使用Control.FindControl方法来获取该控件。

但是,如果您不确切知道哪个控件可能是父控件,则可以编写自定义FindControlRecursive方法来搜索该控件,无论在哪里。

using System.Web.UI;

namespace MyNamespace
{
    public static class ControlExtensions
    {
        public static T FindControlRecursive<T>(this Control parentControl, string id) where T : Control
        {
            T ctrl = default(T);

            if ((parentControl is T) && (parentControl.ID == id))
                return (T)parentControl;

            foreach (Control c in parentControl.Controls)
            {
                ctrl = c.FindControlRecursive<T>(id);

                if (ctrl != null)
                    break;
            }
            return ctrl;
        }
}

然后拨打FindControlRecursive<DropDownList>("ddlSectors")

答案 1 :(得分:0)

感谢Janis

你的想法激励了我。

但这是适用于我的功能

Control FindControl2(ControlCollection col,string desiredID)
    {
        Control found=default(Control);


        if (found != null)
            return found;
            for (int i = 0; i < col.Count; i++)
            {

                Control temp = col[i];
                if (temp != null)
                {
                    if (temp.ID != null)
                    {
                        if (temp.ID == desiredID)
                        {
                            found = temp;
                            break;
                        }
                        else
                        {
                            if (found != null)
                                return found;
                            else
                            found=FindControl2(temp.Controls, desiredID);
                        }
                    }
                    else
                    {
                        if (found != null)
                            return found;
                        else
                        found = FindControl2(temp.Controls, desiredID);
                    }


                }
            }

        return found;
    }

我用过它并且有效

感谢

相关问题