只是爲了讓你開始。
- 用戶控件:DynamicUC.ascx
- 頁使用該用戶控制:DynamicPage.aspx
DyanamicUC.ascx
<div style="float: left">
<asp:TextBox ID="tbMyTextBox" runat="server" />
<asp:GridView runat="server" ID="gvNumbers" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="Serial" HeaderText="Seiral" />
<asp:TemplateField HeaderText="Item Name">
<ItemTemplate>
<%# Eval("Item") %>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
DynamicUC.ascx.cs
public partial class DynamicUC : UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
}
public void PopulateData(string value)
{
tbMyTextBox.Text = value;
gvNumbers.DataSource = Enumerable.Range(1, 5).Select(i => new { Serial = i, Item = "Item " + i });
gvNumbers.DataBind();
}
public string GetData()
{
return Server.HtmlEncode(tbMyTextBox.Text);
}
}
個
DynamicPage.aspx
<asp:Button ID="btnAddUC" Text="Add UC" runat="server" OnClick="btnAddUC_Click" />
<asp:Button ID="btnGetUCValues" Text="Get UC Values" runat="server" OnClick="btnGetUCValues_Click" />
<asp:Panel runat="server" ID="pnlDynamicUCPanel" Style="overflow: auto;">
</asp:Panel>
<asp:Label ID="lblUCValues" runat="server" Style="clear: both;" />
DynamicPage.aspx.cs
public partial class DynamicPage : System.Web.UI.Page
{
private int NumberOfDynamicControls
{
get
{
var numberOfDynamicControls = ViewState["__dynamicUCCount"];
if (numberOfDynamicControls != null)
{
return (int)numberOfDynamicControls;
}
return 0;
}
set
{
ViewState["__dynamicUCCount"] = value;
}
}
private List<DynamicUC> _dynamicUCList;
protected void Page_Load(object sender, EventArgs e)
{
RestoreDynamicUC();
}
protected void btnAddUC_Click(object sender, EventArgs e)
{
CreateDyanamicUC(NumberOfDynamicControls);
NumberOfDynamicControls++;
}
private void RestoreDynamicUC()
{
if (NumberOfDynamicControls == 0)
return;
for (int i = 0; i < NumberOfDynamicControls; i++)
{
CreateDyanamicUC(i);
}
}
private void CreateDyanamicUC(int dataIndex)
{
if (_dynamicUCList == null)
{
_dynamicUCList = new List<DynamicUC>();
}
var dynamicUC = LoadControl("DynamicUC.ascx") as DynamicUC;
dynamicUC.PopulateData("Data " + dataIndex);
pnlDynamicUCPanel.Controls.Add(dynamicUC);
_dynamicUCList.Add(dynamicUC);
}
protected void btnGetUCValues_Click(object sender, EventArgs e)
{
var valuesText = "";
if (_dynamicUCList != null)
{
valuesText = string.Join(", ", _dynamicUCList.Select(duc => duc.GetData()));
}
lblUCValues.Text = "UC Values: " + valuesText;
}
}
有很多解釋;但我恐怕沒有多少時間。但是這應該給一些提示。