我有一個客戶用戶控件AddressControl.ascx,它包含在中繼器控件中。當我的頁面第一次加載時,一切似乎都正常,我的轉發器正在爲Page_Load事件中填充的虛擬地址創建兩個項目。但是,當我點擊添加地址按鈕時,會添加第3個轉發器項目,但現在所有其他轉發器項目都是空的(即屏幕上的所有字段都變空)。中繼器內的ASP.NET自定義用戶控件:動態添加項目
在調試時,我注意到在第一次加載時,AddressControl的Page_Load事件具有地址對象。但是,當我們點擊添加地址按鈕後,我們來到Page_Load時,地址對象爲空。
*注意:添加地址按鈕的目標是讓一組空白控件顯示爲允許用戶輸入新地址。
任何幫助,非常感謝。
AddressControl.ascx
public partial class AddressControl : System.Web.UI.UserControl
{
public Address address { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
if (address != null)
{
txtStreet1.Text = address.Address1;
txtStreet2.Text = address.Address2;
txtCity.Text = address.City;
cboRegion.SelectedIndex = 2;
txtPostalCode.Text = address.PostalCode;
}
}
}
Default.aspx的
<asp:Repeater ID="AddrRepeater" runat="server" OnItemDataBound="AddrRepeater_ItemDataBound">
<ItemTemplate>
<uc1:AddressControl runat="server" id="ctlAddress" />
</ItemTemplate>
</asp:Repeater>
<asp:Button ID="btnAdd" runat="server" text="Add Address" OnClick="btnAdd_Click" />
Default.aspx.cs
public partial class Default : System.Web.UI.Page
{
public List<Address> Addresses
{
get
{
var addresses = HttpContext.Current.Session["addressList"] as List<Address>;
if (addresses == null)
{
addresses = new List<Address>();
HttpContext.Current.Session["addressList"] = addresses;
}
return addresses;
}
set
{
HttpContext.Current.Session["addressList"] = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Addresses = new List<Address>()
{
new Address { Address1 = "123 Main St", Address2 = "", City = "New York", State = "NY", PostalCode = "10001" },
new Address { Address1 = "555 Fake St", Address2 = "", City = "New York", State = "CA", PostalCode = "91367" }
};
AddrRepeater.DataSource = Addresses;
AddrRepeater.DataBind();
}
}
protected void AddrRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
var address = e.Item.DataItem as Address;
var addrCtl = e.Item.FindControl("ctlAddress") as AddressControl;
addrCtl.address = address;
}
}
protected void btnAdd_Click(object sender, EventArgs e)
{
Address newAddress = new Address();
Addresses.Add(newAddress);
AddrRepeater.DataSource = Addresses;
AddrRepeater.DataBind();
}
}