2011-04-22 42 views
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文件的位置。調用具有參數錯誤的WebuserControl -

錯誤76的對象引用是所必需的非靜態字段,方法或屬性「System.Web.UI.TemplateControl.LoadControl(字符串)」

回答

0

你給到LoadControl的第一參數是一個Type和它的價值controlName.GetType().BaseType等於System.ObjectcontrolNamestringstring基本類型是object) - >錯誤類型「System.Object的」不繼承「System.Web.UI.Control」因爲LoadControl預計一System.Web.UI.Control類型。

你想instanciate控制給它的名字&一些參數。不幸的是,沒有版本的LoadControl接受這些參數。幸運的是,實現這一點非常簡單。看看這篇文章:A Good Example of Asp.net LoadControl with multiple parameters

+0

讓我看看,謝謝。一旦完成,我會再回來。 – 2011-04-22 00:25:53