我将以下代码在gridview列中显示为行:
代码背后:
protected void Page_Load(object sender, EventArgs e)
{
gvOrdersProcessed.DataSource = FlipDataTable(BindOrdersProcessed());
gvOrdersProcessed.DataBind();
}
public DataTable BindOrdersProcessed()
{
SqlConnection Conn = new SqlConnection(ConfigurationManager.ConnectionStrings["WO_StatusConnectionString"].ToString());
SqlCommand Cmd = new SqlCommand("sp_B2B_GetOrdersProcessed", Conn);
Cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter ada = new SqlDataAdapter(Cmd);
DataTable dt = new DataTable();
ada.Fill(dt);
return dt;
}
public DataTable FlipDataTable(DataTable dt)
{
DataTable table = new DataTable();
//Get all the rows and change into columns
for (int i = 0; i <= dt.Rows.Count; i++)
table.Columns.Add(Convert.ToString(i));
DataRow dr;
//get all the columns and make it as rows
for (int j = 0; j < dt.Columns.Count; j++)
{
dr = table.NewRow();
dr[0] = dt.Columns[j].ToString();
for (int k = 1; k <= dt.Rows.Count; k++)
dr[k] = dt.Rows[k - 1][j];
table.Rows.Add(dr);
}
return table;
}
在我的HTML中:
<div id="GridOrdersProcessed">
<asp:GridView ID="gvOrdersProcessed" runat="server">
</asp:GridView>
</div>
现在运行以上内容时,我将数字作为标题:
0 1 2 3 4 5 6
DateCreate 02/11/2013 02/19/2013 02/21/2013 02/25/2013 02/26/2013 02/27/2013
OrdersPendingInvoice 0 0 0 0 0 0
OrdersPendingPickUp 1 1 2 1 7 9
为什么会这样?
另外,如何添加一个包含以下总订单的新列:
DateCreate Total 02/11/2013 02/19/2013 02/21/2013 02/25/2013 02/26/2013 02/27/2013
OrdersPendingInvoice 0 0 0 0 0 0 0
OrdersPendingPickUp 21 1 1 2 1 7 9
答案 0 :(得分:1)
您正在将数字作为标题,因为您已在此处创建了带有数字名称的DataColumns:
public DataTable FlipDataTable(DataTable dt)
{
DataTable table = new DataTable();
//Get all the rows and change into columns
for (int i = 0; i <= dt.Rows.Count; i++)
table.Columns.Add(Convert.ToString(i));
你可能想要这样的事情:
for (int i = 0; i < dt.Rows.Count; i++)
table.Columns.Add(Convert.ToString(dt.Rows[i][0]));
另请注意,我已在循环中将<=
更改为i <
。
编辑:但我担心该方法不符合预期(反转行和列的角色也称为 pivot )。
您可以使用此扩展方法:
public static DataTable Pivot(this DataTable tbl)
{
var tblPivot = new DataTable();
tblPivot.Columns.Add(tbl.Columns[0].ColumnName);
for (int i = 1; i < tbl.Rows.Count; i++)
{
tblPivot.Columns.Add(Convert.ToString(i));
}
for (int col = 0; col < tbl.Columns.Count; col++)
{
var r = tblPivot.NewRow();
r[0] = tbl.Columns[col].ToString();
for (int j = 1; j < tbl.Rows.Count; j++)
r[j] = tbl.Rows[j][col];
tblPivot.Rows.Add(r);
}
return tblPivot;
}
更新也许这个linq查询有助于在转动表格之前获取总列数:
int OrdersPendingInvoiceTotal= tbl.AsEnumerable()
.Sum(r => r.Field<int>("OrdersPendingInvoice"));
int OrdersPendingPickUpTotal= tbl.AsEnumerable()
.Sum(r => r.Field<int>("OrdersPendingPickUp"));