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方法,我已经从保护方法转变为公共静态方法。Im得到第一个参数的错误,即润湿器控制.ascx文件的位置。
错误76非静态字段、方法或属性'System.Web.UI.TemplateControl.LoadControl(string)‘需要对象引用。
发布于 2011-04-22 00:23:16
您要给LoadControl的第一个参数是Type,它的值controlName.GetType().BaseType等于System.Object (controlName是string,string是object的基本类型) ->错误类型'System.Object‘不能继承'System.Web.UI.Control’,因为LoadControl需要System.Web.UI.Control类型。
您希望实例化一个给出它的名称的控件&一些参数。不幸的是,没有接受这些参数的LoadControl版本。幸运的是,要做到这一点很简单。看看这篇文章:。
https://stackoverflow.com/questions/5751115
复制相似问题