我有一个类似的课程:
public class ApplicationInformation
{
public string ApplicationName { get; set; }
public List<UserInformation> Users { get; set; }
}
我想在DataGrid中显示List<ApplicationInformation>
。所以我尝试了这个:
.aspx:
<asp:DataGrid ID="tbl" runat="server">
</asp:DataGrid>
.aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
tbl.DataSource = Global.Data;
tbl.DataBind();
}
但该表只有一个标题为ApplicationName
的列。我希望ApplicationInformation
和UserInformation
中的每个属性都有一列,UserInformation
列表中的每个List<ApplicationInformation>
都有一个单独的行。
我希望这是有道理的......
我稍微调查了模板,但无法弄清楚如何做到这一点。我想我总是可以循环遍历所有内容并使用我需要的所有数据创建一个单独的数组,但是我必须创建另一个类,而这似乎不是最好的方法。
修改 的
例如,如果我有这样的List<ApplicationInformation>
:
{
{ ApplicationInformation
ApplicationName = "App 1"
{ UserInformation
UserName = "John Smith"
ApplicationHost = "JOHN-PC"
}
{ UserInformation
UserName = "Mindy from the network"
ApplicationHost = "MINDY-PC"
}
}
{ ApplicationInformation
ApplicationName = "App 2"
{ UserInformation
UserName = "John Smith"
ApplicationHost = "JOHN-PC"
}
{ UserInformation
UserName = "Bob Jones"
ApplicationHost = "BOB-PC"
}
}
}
然后我希望表格显示如下:
Application Name | User Name | Application Host
-------------------------------------------------------
App 1 | John Smith | JOHN-PC
App 1 | Mindy fro...| MINDY-PC
App 2 | John Smmith | JOHN-PC
App 2 | Bob Jones | BOB-PC
答案 0 :(得分:0)
您可以处理ItemDataBound事件或使用linq创建匿名对象并将其绑定到DataGrid
答案 1 :(得分:0)
您可以通过Linq构建anonymous
或typed
列表:
if (!IsPostBack)
{
List<ApplicationInformation> app = new List<ApplicationInformation>()
{
new ApplicationInformation()
{
ApplicationName="App 1",
Users=new List<UserInformation>()
{
new UserInformation()
{
UserName = "John Smith",
ApplicationHost = "JOHN-PC"
},
new UserInformation()
{
UserName = "Mindy from the network",
ApplicationHost = "MINDY-PC"
}
}
},
new ApplicationInformation()
{
ApplicationName="App 2",
Users=new List<UserInformation>()
{
new UserInformation()
{
UserName = "John Smith",
ApplicationHost = "JOHN-PC"
},
new UserInformation()
{
UserName = "Bob",
ApplicationHost = "BOB-PC"
}
}
}
};
var result = from ele in app
from user in ele.Users
select new
{
ApplicationName=ele.ApplicationName,
UserName=user.UserName ,
ApplicationHost=user.ApplicationHost
};
GridView1.DataSource = result.ToList();
GridView1.DataBind();
}
答案 2 :(得分:0)
你需要像Junaid建议的那样处理RowDataBound,但是你需要有一个模板列,它本身可以是另一个Datagrid或某种类型的List来绑定List<UserInformation>
。
例如(未经测试的代码):
void CustomersGridView_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
//find nested grid
GridView nestedGrid = e.FindControl("NestedGridID") as GridView;
nestedGrid.DataSource = DataBinder.Eval(e.DataItem,"Users");
nestedGrid.DataBind();
}
}