Displaying Nested Class Data in an ASP.Net DataGrid
I have a user object which consist of some data and other classes of data:
[DataContract]
public class User
{
[DataMember(Order = 0)]
public int UserId
{
get; set;
}
public UserCredentials UserCredentials
{
get; set;
}
[DataMember(Order = 1)]
public String SessionId { get; set; }
[DataMember(Order = 2)]
public Email Email
{
get; set;
}
[DataMember(Order = 3)]
public Password Password
{
get; set;
}
[DataMember(Order = 4)]
public UserDetails UserDetails
{
get; set;
}
[DataMember(Order = 5)]
public ReferralDetails ReferralDetails
{
get; set;
}
If i display a list of this in ASP.NET datagrid as follows:
List<U开发者_运维知识库sers> users = // get some list of users
DataGridUsers.DataSource = users;
DataGridUsers.DataBind();
This displays sessionId and userId but no other data fields because they are not basic types. What is my solution?
Thanks!
Here is one solution I came up with but I don't like the fact that if you change the User model, add a field or w/e you have to then update this set of code:
//......
DataTable dt = new DataTable();
// Add all columns needed here
dt.Columns.Add(new DataColumn("FirstName", typeof (String)));
// ....
foreach (var user in users)
{
DataRow dr = dt.NewRow();
// Map all the data here
dr["FirstName"] = user.UserDetails.FirstName;
// ...
dt.Rows.Add(dr);
}
DataGridUsers.DataSource = dt;
DataGridUsers.DataBind();
精彩评论