在Asp.net网页中使用接口

本文介绍在ASP.NET开发中如何通过定义接口实现aspx页面与WebUserControl之间的数据交互,解决因控件ID动态变化导致的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在开发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:

ExpandedBlockStart.gif 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实作上面这个接口:

ExpandedBlockStart.gif 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控件赋值:

ExpandedBlockStart.gif 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

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值