Hi Waghmare,
Please take reference the below code and correct your code.
HTML
<asp:GridView ID="GridView1" CssClass="Grid" HeaderStyle-CssClass="header" runat="server"
AutoGenerateColumns="true">
</asp:GridView>
<br />
<asp:Button ID="btnConvert" runat="server" Text="Convert Rows to Columns" OnClick="Convert" />
Namespaces
C#
using System.Data;
Code
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[] { new DataColumn("FormID"), new DataColumn("FieldName"), new DataColumn("Value") });
dt.Rows.Add(1, "MAKE", "SONY");
dt.Rows.Add(2, "MODEL", "VIAO");
dt.Rows.Add(3, "HDD", "500GB");
ViewState["dt"] = dt;
BindGrid(dt, false);
}
}
private void BindGrid(DataTable dt, bool rotate)
{
GridView1.ShowHeader = !rotate;
GridView1.DataSource = dt;
GridView1.DataBind();
if (rotate)
{
foreach (GridViewRow row in GridView1.Rows)
{
row.Cells[0].CssClass = "header";
}
}
}
protected void Convert(object sender, EventArgs e)
{
DataTable dt = (DataTable)ViewState["dt"];
dt.Columns.RemoveAt(0);
DataTable dt2 = new DataTable();
for (int i = 0; i <= dt.Rows.Count; i++)
{
dt2.Columns.Add();
}
for (int i = 1; i < dt.Columns.Count; i++)
{
dt2.Rows.Add("SR.No");
dt2.Rows.Add(i);
dt2.Rows[i][i + 1] = dt.Columns[i].ColumnName;
}
for (int i = 0; i < dt.Columns.Count; i++)
{
for (int j = 0; j < dt.Rows.Count; j++)
{
dt2.Rows[i][j + 1] = dt.Rows[j][i];
}
}
BindGrid(dt2, true);
}
Screenshot