Binding list of objects to ListView with a UserControl inside, problem
I have a ListView containing a UserControl with a public property MyPublicProperty of type MyType.
public MyType MyPublicProperty{ get; set; }
I bind to ListView a list of items of MyType
listView.DataSource = (List<MyType>) items;
listView.DataBind();
In aspx my ListView is defined like this
<asp:ListView ID="listView" runat="server">
<ItemTemplate>
<uc1:MyControl ID="myControl" runat="server" MyPublicProperty="<%#(MyType)Container.DataItem %>" />
</ItemTemplate>
</asp:ListView>
Now what happens is that in MyControl MyPublicProperty is not set at the event onDataBinding, and neither after that event.
Do you happen to know why, and a solution for this ?? EDIT: Looking more into the problems I observed that
listView.Items[0].DataItem
is null after I call listView.DataBind(), but the list datasource has 开发者_运维知识库more then 1 items.
If you want to access the data after it has been bound, you should use the ItemDataBound event which will get called for each item of data:
listView.ItemDataBound += new EventHandler<ListViewItemEventArgs>(listView_ItemDataBound);
Then:
private void listView_ItemDataBound(object sender, ListViewItemEventArgs e)
{
if (e.Item.ItemType == ListViewItemType.DataItem)
{
MyType data = (MyType)((ListViewDataItem)e.Item).DataItem;
// Use your data...
}
}
What is it you're trying to achieve? The way you have your code now, the data will be set in the UserControl just fine without any further work from you.
精彩评论