【发布时间】:2017-03-23 07:19:16
【问题描述】:
我有一个网格视图,我不想在其中显示两列的标题文本,并且两列应该具有相同的标题名称 (INFA)。 Gridview 看起来像:
<asp:GridView ID="GridView6" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="DayOfWeek" HeaderText="" ItemStyle-Width="30" />
<asp:BoundField DataField="DateOfMonth" HeaderText="" ItemStyle-Width="30" />
<asp:BoundField DataField="Emp_Name" HeaderText="INFA" ItemStyle-Width="30" />
<asp:BoundField DataField="Group_Name" HeaderText="INFA" ItemStyle-Width="30" />
<asp:BoundField DataField="Emp_Id" HeaderText="Mainframe" ItemStyle-Width="30" />
</Columns>
</asp:GridView>
我需要翻转这个 gridview 并将行变成列,将列变成行。当我在所有数据字段的标题文本中使用不同的名称时,逻辑工作正常。但在我的要求中,我不需要两列的标题文本,并且两列必须具有相同的标题文本(如 Gridview 中所示)。当我运行没有列名的逻辑时,如上所示,我收到此错误:
Exception Details: System.Data.DuplicateNameException: A column named ' ' already belongs to this DataTable.
我的逻辑是:
protected void btnConvert_Data()
{
System.Data.DataTable dt = new System.Data.DataTable("GridView_Data");
foreach (TableCell cell in GridView6.HeaderRow.Cells)
{
if (cell.Text == "")
{
dt.Columns.Add("");
}
else
{
dt.Columns.Add(cell.Text);
}
}
dt.Rows.Add("IST Hours");
//dt.Rows.Add("8:45AM-6PM");
foreach (GridViewRow row in GridView6.Rows)
{
dt.Rows.Add();
for (int i = 0; i < row.Cells.Count; i++)
{
dt.Rows[dt.Rows.Count - 1][i] = row.Cells[i].Text;
}
}
gvColumnsAsRows.DataSource = FlipDataTable(dt);
gvColumnsAsRows.DataBind();
gvColumnsAsRows.HeaderRow.Visible = false;
}
将行翻转为列,反之亦然:
public static System.Data.DataTable FlipDataTable(System.Data.DataTable dt)
{
System.Data.DataTable table = new System.Data.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;
}
我在 dt.Columns.Add(cell.Text); 行的 btnConvert_Data() 中遇到上述错误。谁能帮我解决这个问题?
我翻转 Gridview 时的最终输出应如下所示:
【问题讨论】:
-
谁能帮我解决这个问题?