分享

在Asp.net网页中使用接口

 悟静 2012-09-22

在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

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();
    }
}
复制代码


WebUserControl实作上面这个接口

InsusUc
复制代码
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控件赋值:

View Code
复制代码
 private void Data_Binding()
    {
        CheckBoxList cbl 
= ((IGetable)this
.InsusUc1).GetControl();
        cbl.DataSource 
=
 ProductCode;
        cbl.DataTextField 
= "value"
;
        cbl.DataValueField 
= "key"
;
        cbl.DataBind();
    }
复制代码


 程序运行时的效果:

 

源程序下载:
地址:
http://download.cnblogs.com/insus/ASPDOTNET/InterfaceDemo.rar

 

 

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多