我试图遍历多个站点URL以获取以表格形式返回的数据,我遇到的问题是当我将数据源绑定到gridview时它覆盖了以前的foreach,我怎样才能将所有数据写入一个网格视图?我的代码如下。 谢谢!
foreach (SPListItem item in items)
{
string url = item["SiteUrl"].ToString();
using (SPSite siteadd = new SPSite(url))
using (SPWeb webadd = siteadd.OpenWeb())
{
//
DataGrid grd = null;
grd = new DataGrid();
DataTable table = webadd.GetUsageData(Microsoft.SharePoint.Administration.SPUsageReportType.browser, Microsoft.SharePoint.Administration.SPUsagePeriodType.lastMonth);
if (table == null)
{
// HttpContext.Current.Response.Write("Table Null");
}
else
{
dataGridView1.DataSource = table;
}
}
}
答案 0 :(得分:0)
不应将.DataSource设置为'table',而应将表中的Rows添加到.DataSource表中。这将导致APPEND。
答案 1 :(得分:0)
您创建一个数据行,然后向其添加行,如下面的代码
//This Section should be outside your loop
DataTable dt = new DataTable();
DataColumn dc = new DataColumn("col1", typeof(String));
dt.Columns.Add(dc);
dc = new DataColumn("col2", typeof(String));
dt.Columns.Add(dc);
dc = new DataColumn("col3", typeof(String));
dt.Columns.Add(dc);
dc = new DataColumn("col4", typeof(String));
dt.Columns.Add(dc);
//End of section
//Inside your loop
DataRow dr = dt.NewRow();
dr[0] = "coldata1";
dr[1] = "coldata2";
dr[2] = "coldata3";
dr[3] = "coldata4";
dt.Rows.Add(dr);
答案 2 :(得分:0)
不是将单个站点数据表绑定到Datagrid,而是应该在循环外创建另一个数据表,该数据表将包含来自所有单个项目的数据,如下所示:
DataTable aggregatedTable = new DataTable();
foreach (SPListItem item in items)
{
string url = item["SiteUrl"].ToString();
using (SPSite siteadd = new SPSite(url))
using (SPWeb webadd = siteadd.OpenWeb())
{
//
DataGrid grd = null;
grd = new DataGrid();
DataTable table = webadd.GetUsageData(Microsoft.SharePoint.Administration.SPUsageReportType.browser, Microsoft.SharePoint.Administration.SPUsagePeriodType.lastMonth);
if (table == null)
{
// HttpContext.Current.Response.Write("Table Null");
}
else
{
aggregatedTable.Merge(table);//Append the data to previous site data.
}
}
}
dataGridView1.DataSource = aggregatedTable;//bind datatable with aggregated data