Repeater binding dictionary data source code and error resolution

  • 2020-06-03 06:13:35
  • OfStack

.aspx page code
 
<asp:Repeater ID="Repeater1" runat="server"> 
<ItemTemplate> 
<%# ((KeyValuePair<int, List<User>>)Container.DataItem).Key %> <br /> 
<asp:Repeater ID="Repeater2" runat="server" DataSource='<%# ((KeyValuePair<int, List<User>>)Container.DataItem).Value %>'> 
<ItemTemplate> 
<%# (Container.DataItem as User).Id %> 
<%# (Container.DataItem as User).Name %> 
</ItemTemplate> 
</asp:Repeater> 
<hr /> 
</ItemTemplate> 
</asp:Repeater> 

.aspx. cs postcode
 
public partial class Temp : System.Web.UI.Page 
{ 
Dictionary<int, List<User>> dict = new Dictionary<int, List<User>>(); 
protected void Page_Load(object sender, EventArgs e) 
{ 
dict.Add(1, new List<User> 
{ 
new User{Id = 1, Name = "aa"} 
,new User{Id = 2, Name = "bb"} 
}); 
dict.Add(2, new List<User> 
{ 
new User{Id = 3, Name = "cc"} 
,new User{Id = 4, Name = "dd"} 
}); 
Repeater1.DataSource = dict; 
Repeater1.DataBind(); 
} 
} 
public class User 
{ 
public int Id{get;set;} 
public string Name{get;set;} 
} 

If the following error is reported:
repeater USES an invalid data source. Valid data sources must implement IListSource or IEnumerable?
This is because of the data source type issue, such as the DataTable DataSet Xml Arrry collection
A type like the String int object cannot be used directly as its data source, especially if the object causes problems

Related articles: