public void xMain()
{
DataTable dt = new DataTable();
dt.Columns.Add("product");
dt.Columns.Add("name");
dt.Columns.Add("result");
dt.Columns.Add("date");
for (int i = 1; i < 5; i++)
{
DataRow dr = dt.NewRow();
dr["product"] = "product" + i;
dr["name"] = "name" + i;
dr["result"] = i + 5;
dr["date"] = "2011-11-11";
dt.Rows.Add(dr);
}
for (int i = 1; i < 5; i++)
{
DataRow dr = dt.NewRow();
dr["product"] = "product" + i;
dr["name"] = "name" + i;
dr["result"] = i;
dr["date"] = "2011-11-12";
dt.Rows.Add(dr);
}
for (int i = 1; i < 5; i++)
{
DataRow dr = dt.NewRow();
dr["product"] = "product" + i;
dr["name"] = "name" + i;
dr["result"] = i + 4;
dr["date"] = "2011-11-13";
dt.Rows.Add(dr);
}
for (int i = 1; i < 5; i++)
{
DataRow dr = dt.NewRow();
dr["product"] = "product" + i;
dr["name"] = "name" + i;
dr["result"] = i + 3;
dr["date"] = "2011-11-14";
dt.Rows.Add(dr);
}
for (int i = 4; i < 6; i++)
{
DataRow dr = dt.NewRow();
dr["product"] = "product" + i;
dr["name"] = "name" + i;
dr["result"] = i+2;
dr["date"] = "2011-11-15";
dt.Rows.Add(dr);
}
GridView2.DataSource = dt;
GridView2.DataBind();
DisplayTable(ColumnToRow(dt,3,2,0));
}
public void DisplayTable(DataTable dt) {
GridView1.DataSource = dt;
GridView1.DataBind();
}
#region DataTable 行转列
public List<string> SelectDistinct(DataTable SourceTable,int key)//去除重复项
{
List<string> li=new List<string>();
foreach (DataRow dr in SourceTable.Rows)
{
if (!li.Contains(dr[key].ToString()))
{
li.Add(dr[key].ToString());
}
}
return li;
}
/// <summary>
/// ColumnToRow
/// </summary>
/// <param name="src_dt">源表</param>
/// <param name="columnIndex">需要行做列名的列索引</param>
/// <param name="columnValue">需要行做列值列索引</param>
/// <param name="key">分组的列索引</param>
/// <returns></returns>
public DataTable ColumnToRow(DataTable src_dt, int columnIndex,int columnValue,int key ) //columnIndex 用来当作新列名的列
{
int n = src_dt.Columns.Count;
DataTable dt = new DataTable();
List<string> li = SelectDistinct(src_dt, key);
List<string> lt = SelectDistinct(src_dt, columnIndex);
for (int d = 0; d < n; d++)
{
if (d == columnIndex)
{
foreach (var item in lt)
{
dt.Columns.Add(item);
}
}
else {
if (d == columnIndex || d == columnValue) continue; //如果是被当作列名的列,则跳过
dt.Columns.Add(src_dt.Columns[d].ColumnName);
}
}
int j = 0;
string newColumnName = null;
DataRow new_dr = null;
foreach (var item in li)
{
new_dr = dt.NewRow();
for (int i = 0; i < n; i++)
{
foreach (DataRow dr2 in src_dt.Select(src_dt.Columns[key].ColumnName+ "='" + item + "'"))
{
if (i == columnIndex)
{
newColumnName = dr2[columnIndex].ToString();
new_dr[newColumnName] = dr2[columnValue];
}
else
{
if (i == columnValue || i == columnValue) continue; //如果是被当作列名的列,则跳过
newColumnName = src_dt.Columns[i].ColumnName;
new_dr[newColumnName] = dr2[i];
}
}
}
dt.Rows.Add(new_dr);
newColumnName = null;
j++;
}
return dt;
}
#endregion
页面建两个GridView 就可以测试
我不知道这个效率如何,请大神们给点意见,3Q