• 动态加载并获取usercontrol生成的html


        在项目中用户控件往往是html代码的生成工具,在aspx页面中添加其引用就可以获取它所生成的html代码

        以供显示。但如何在后台代码.cs文件中动态的加载并获取其html代码就不容易了,以下是我研究的心得。

        方案一: 在用户控件中添加公共属性和公共方法以供外部程序调用。

    ddl.ascx.cs code:

    public
    partial class ddl : System.Web.UI.UserControl { public List<string> sourceList { get; set; } //公共属性 public void setValue() //公共方法 { List<string> currentSource = this.sourceList; foreach (string str in currentSource) { ListItem item = new ListItem(); item.Value = str; item.Text = str; _ddl.Items.Add(item); } } }
     
    userControlTest.aspx.cs code:

    protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { List<string> testList=new List<string> (); testList.Add("xiaochun"); testList.Add("xiaochun"); testList.Add("xiaochun"); testList.Add("xiaochun"); testList.Add("xiaochun"); StringWriter sw = new StringWriter(); HtmlTextWriter writer = new HtmlTextWriter(sw); UserControl userControl = new UserControl(); string pathString = "/usercontrol/ddl.ascx"; //注意这里不能为绝对路径 ddl currentControl= userControl.LoadControl(pathString) as ddl; currentControl.sourceList = testList; //调用公共属性 currentControl.setValue(); //调用公共方法 if (currentControl is ddl) { currentControl.RenderControl(writer); Response.Write( sw.ToString()); } } }

       方案二:采用一个公共类A去继承 System.Web.UI.UserControl,然后再在其中添加接口。然后usercontrol去继承这个公共类A然后

                  再去实现类A中的接口。

                 公共类 BaseQueryControl

        public abstract class BaseQueryControl:UserControl  //注意这里要继承UserControl
        {
            public abstract void SetDataSourceBind(object source); //这里是接口
        }

                用户控件

     public partial class EnumeratorControl : BaseQueryControl //继承公共类
        {public override void SetDataSourceBind(object source) //重载方法
            {
                if (source!=null)
                {
                    this.ddl.DataSource = source;
                    this.ddl.DataBind();                
                }
            }
    }

                  这样做有一个好处,就是可以统一管理继承了类A的所以usercontrol。

  • 相关阅读:
    UVa 10118 记忆化搜索 Free Candies
    CodeForces 568B DP Symmetric and Transitive
    UVa 11695 树的直径 Flight Planning
    UVa 10934 DP Dropping water balloons
    CodeForces 543D 树形DP Road Improvement
    CodeForces 570E DP Pig and Palindromes
    HDU 5396 区间DP 数学 Expression
    HDU 5402 模拟 构造 Travelling Salesman Problem
    HDU 5399 数学 Too Simple
    CodeForces 567F DP Mausoleum
  • 原文地址:https://www.cnblogs.com/msql/p/2848100.html
Copyright © 2020-2023  润新知