I would like to know the best way to directly assign properties to a dynamically created UserControl bound to an asp:Repeater. Consider the following code.
In the codebehind for the UserControl "MyControlType":
public bool IsRetained = false;
In the Page code:
<%@Register TagPrefix="pre" TagName="MyControlType" Src="~/MyPath/MyControl.ascx" %>
<asp:Repeater ID="repeater" DataSource='<%#dataSource%>' runat="server">
<ItemTemplate>
<pre:MyControlType runat="server" />
</ItemTemplate>
</asp:Repeater>
<asp:Button OnClick="someButton_Click" Text="Add First Item" runat="server" />
In the Page codebehind:
protected List<MyControlType> dataSource = new List<MyControlType>();
protected void someButton_Click(object sender, EventArgs e)
{
MyControlType myItem = (MyItem)Page.LoadControl("~/MyMath/MyControlType.ascx");
dataSource.Add(myItem);
myItem.IsRetained = true;
repeater.DataBind();
// test code
MyControlType realItem = repeater.Items[0].Controls[1] as MyControlType;
bool test0 = realItem.IsRetained; // false
bool test1 = myItem == realItem; // false
}
A new MyControlType is successfully bound to the Repeater and displayed on the page, but it does not have the IsRetained value that I set. It is also not the same MyControlType instance as the one that I assigned to dataSource.
I can accomplish what I want to by obtaining a reference to the created MyControlType similarly to how I did with realItem in the example above, but I would prefer assign the property directly through myItem. Can anyone provide a method of doing so? It would also be nice to understand why test0 and/or test1 are false. Thanks!