從程式端動態加入多個UserControl

自己在玩寫一個購物網站的時候,有個需求就是查詢歷史購物清單,原本打算在該查詢畫面使用動態的方式畫出多個GridView,但是真正要寫的時候發現動態產生多個GridView還要從程式多加入GridView的Template等等...,有點麻煩,於是就想說從UC來下手。
下面我首先說明UC的程式碼的部份。

UC在.aspx檔的部份先劃出一個GirdView和藏一個HiddenField,隱藏欄位的目的是為了記住UC的屬性,為了看的更清楚,我先放一個TextBox,語法如下。
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="OrderListHistoryGridView.ascx.cs"
Inherits="OrderListHistoryGridView" %>
<asp:TextBox ID="Input_OrderListID" runat="server"></asp:TextBox>
<asp:GridView ID="GridView1" runat="server" Width="100%" AutoGenerateColumns="false">
<columns>
<asp:BoundField DataField="no" HeaderText="商品代碼" />
<asp:BoundField DataField="productname" />
<asp:BoundField DataField="quantity" HeaderText="數量" />
<asp:BoundField DataField="amount" HeaderText="單價" />
<asp:BoundField DataField="totalamount" HeaderText="小計" />
</Columns>
<emptydatatemplate>
<asp:Label runat="server" ID="Label_Empty" Text="尚無任何資料"></asp:Label>
</EmptyDataTemplate>
<headerstyle BackColor="Black" ForeColor="White" BorderColor="Red" Height="30px" />
<rowstyle Height="25px" BackColor="" />
<alternatingrowstyle BackColor="#E0E3FE" />
<rowstyle />
<selectedrowstyle BackColor="#738A9C" Font-Bold="True" ForeColor="#F7F7F7" />
</asp:GridView>

UC在.cs檔的部份首先宣告一個屬性,接下來在Page_Load的地方就處理資料繫結的部份(在這裡不再說明)。
//屬性宣告
public string OrderListID
{
get { return this.Input_OrderListID.Text; }
set { this.Input_OrderListID.Text = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = conn.DataTable();
this.GridView1.DataSource = dt;
this.GridView1.DataBind();
}

接下來就是如何使用了,再要呼叫的AP程式碼中直接使用下面語法跑迴圈呼叫多個UC即可。
using (IDataReader dr = conn.ExecuteReader())
{
while (dr.Read())
{
Control gridview = this.Page.LoadControl("~/Layout/uc/OrderListHistoryGridView.ascx");
gridview.GetType().GetProperty("OrderListID").SetValue(gridview, dr["id"].ToString(), null);
//Panel1先在.ASPX檔拉的物件
this.Panel1.Controls.Add(gridview);
}
}


程式執行畫面如下

留言