2016年3月29日 星期二

[ASP.NET] 使用 acsx 與 aspx - WebUserControl


簡單的說「就是把元件放在 ascx 上,然後在 aspx 裡使用」。
今天舉的例子就是在 ascx 裡放入 DataGrid 然後在 aspx 裡呼叫,並以 findcontrol 方式來連結設定相關的屬性。

Ascx 內容

在  WebuserControl 放上
<asp:DataGrid runat ="server"  ID ="gd"></asp:DataGrid>

Aspx 使用 Ascx

在Aspx放上要使用的元件,用DataGrid」當範例。

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="xx" Inherits="xxx" %>
<%@ Register TagPrefix ="wuc" TagName ="wuc1" Src ="~/WebUserControl1.ascx" %>
TagPrefix ="wuc"wuc 可自行定義。
TagName ="wuc1"wuc1 可自行定義。

<body> 
      <wuc:wuc1 ID="wuc1" runat="server" />
</body>

findcontrol 對應 ascx 裡的元件

元件是放在 ascx 裡,
所以在 apsx 裡要應用就必須先用 findcontrol 把他對應起來,
底下簡單的例子,是將 findcontrol 的動作寫在 page_load
然後指定 SqlDataSource 接著 bind 起來

protected void Page_Load(object sender, EventArgs e)
{
       DataGrid gd1 = new DataGrid();
       gd1 = (DataGrid)wuc1.FindControl(gd);
       gd1.DataSource = SqlDataSource1;
       gd1.DataBind ();
}

黃昏的甘蔗