在Asp.net网页中使用接口
生活随笔
收集整理的這篇文章主要介紹了
在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實作上面這個接口:
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
?
?
總結
以上是生活随笔為你收集整理的在Asp.net网页中使用接口的全部內容,希望文章能夠幫你解決所遇到的問題。