在Asp.net网页中使用接口在开发Asp.net时,我们会经常有应用MasterPage或是WebUserControl。这样会遇上一个问题,需要在aspx去找MasterPage或是WebUserControl内的对象,或是从aspx传值给它们。比如一个WebUserControl被aspx调用之后,它产生的ID会随着aspx的环境而变化,而不是一成不变的,因为假如使用FindControl()寻找的话,当ID发生变化,在aspx 运行时会发生异常。下面就以一个WebUserControl来演示。 这个WebUserControl会放一个CheckBoxList控件,当这个WebUserControl拉到aspx页面去时,在asps.cs给这个WebUserControl内的CheckBoxList控件绑定数据源。 写一个接口类别IGetable: ![]() using System;
using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI.WebControls; /// <summary> /// Summary description for IGetable /// </summary> namespace Insus.NET { public interface IGetable { CheckBoxList GetControl(); } }
![]() using System;
using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using Insus.NET; public partial class InsusUc : System.Web.UI.UserControl,IGetable { protected void Page_Load(object sender, EventArgs e) { } public CheckBoxList GetControl() { return this.CheckBoxList1; } }
最后是页面aspx.cs为WebUserControl的CheckBoxList控件赋值: ![]() private void Data_Binding()
{ CheckBoxList cbl = ((IGetable)this.InsusUc1).GetControl(); cbl.DataSource = ProductCode; cbl.DataTextField = "value"; cbl.DataValueField = "key"; cbl.DataBind(); }
源程序下载:
|
|
来自: 悟静 > 《.net和asp.net》