0
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Web.Services;
using System.Text;
using System.IO;
using System.Reflection;

namespace e_compro
{
    public partial class fetchrepeater : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        [WebMethod]
        public static string Result(string controlName)
        {
           // return RenderControl(controlName);
            Control toreturn = LoadControl(controlName, "hello");
            return toreturn;
        }

        //public static string RenderControl(string controlName)
        //{
        //    Page page = new Page();
        //    UserControl userControl = (UserControl)page.LoadControl(controlName);
        //    userControl.EnableViewState = false;
        //    HtmlForm form = new HtmlForm();
        //    form.Controls.Add(userControl);
        //    page.Controls.Add(form);

        //    StringWriter textWriter = new StringWriter();
        //    HttpContext.Current.Server.Execute(page, textWriter, false);
        //    return textWriter.ToString();
        //}

        public static UserControl LoadControl(string UserControlPath, params object[] constructorParameters)
        {
            List<Type> constParamTypes = new List<Type>();
            foreach (object constParam in constructorParameters)
            {
                constParamTypes.Add(constParam.GetType());
            }

            UserControl ctl = Page.LoadControl(UserControlPath) as UserControl;

            // Find the relevant constructor
            ConstructorInfo constructor = ctl.GetType().BaseType.GetConstructor(constParamTypes.ToArray());

            //And then call the relevant constructor
            if (constructor == null)
            {
                throw new MemberAccessException("The requested constructor was not found on : " + ctl.GetType().BaseType.ToString());
            }
            else
            {
                constructor.Invoke(ctl, constructorParameters);
            }

            // Finally return the fully initialized UC
            return ctl;
        }


    }
}

我已将 LoadControl 方法的受保护静态方法更改为公共静态方法。第一个参数是 Webuser 控件 .ascx 文件的位置,我收到此错误。

错误 76 非静态字段、方法或属性“System.Web.UI.TemplateControl.LoadControl(string)”需要对象引用

4

1 回答 1

0

您提供给 LoadControl 的第一个参数是 a Type,它的值controlName.GetType().BaseType等于System.ObjectcontrolName是 astringstringis的基类型object)-> 错误类型“System.Object”不继承自“System.Web.UI.Control”,因为LoadControl需要一个System.Web.UI.Control类型。

你想实例化一个控件,给出它的名字和一些参数。不幸的是,没有LoadControl接受这些参数的版本。幸运的是,实现这一目标非常简单。看看这篇文章:A Good Example of Asp.net LoadControl with multiple parameters

于 2011-04-22T00:23:16.313 回答