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 メソッドを protected から public static メソッドに変更しました。Webuser コントロールの .ascx ファイルの場所である最初のパラメーターでこのエラーが発生します。

エラー 76 非静的フィールド、メソッド、またはプロパティ 'System.Web.UI.TemplateControl.LoadControl(string)' にはオブジェクト参照が必要です

4

1 に答える 1

0

LoadControl に指定している最初のパラメーターは aTypeであり、その値controlName.GetType().BaseTypeSystem.Object( controlNameis でありstring、ベースタイプはstringis 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 に答える