Hi,
Please refer below code.
HTML
<div>
<asp:GridView ID="GridView1" CssClass="Grid" HeaderStyle-CssClass="header" runat="server"
OnRowDataBound="RowDataBound" AutoGenerateColumns="true">
</asp:GridView>
<br />
<asp:Button ID="btnConvert1" runat="server" Text="Convert Rows to Columns" OnClick="Convert"
CommandArgument="1" />
<asp:Button ID="btnConvert2" runat="server" Text="Convert Columns to Rows" OnClick="Convert"
CommandArgument="2" Visible="false" />
</div>
C#
// You need to set it as per your DataTable column
private int ImageColumnIndex = 3;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[] { new DataColumn("Item"), new DataColumn("Quantity"), new DataColumn("Price"), new DataColumn("Image"), new DataColumn("Total") });
dt.Rows.Add("Chrysanthemum", 145, 500, "~/Images/Chrysanthemum.jpg", 72500);
dt.Rows.Add("Hydrangeas", 0, 2000, "~/Images/Hydrangeas.jpg", 0);
dt.Rows.Add("Jellyfish", 190, 1545, "~/Images/Jellyfish.jpg", 293550);
dt.Rows.Add("Penguins", 30, 200, "~/Images/Penguins.jpg", 6000);
ViewState["dt"] = dt;
BindGrid(dt, false);
}
}
protected void RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (!btnConvert2.Visible)
{
Image img = new Image();
img.ImageUrl = e.Row.Cells[ImageColumnIndex].Text;
img.Height = 100;
img.Width = 100;
e.Row.Cells[ImageColumnIndex].Controls.Add(img);
}
else
{
if (e.Row.RowIndex == ImageColumnIndex)
{
for (int i = 1; i < e.Row.Cells.Count; i++)
{
TableCell cell = e.Row.Cells[i];
Image img = new Image();
img.Height = 100;
img.Width = 100;
img.ImageUrl = e.Row.Cells[i].Text;
cell.Controls.Add(img);
}
}
}
}
}
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"];
if ((sender as Button).CommandArgument == "1")
{
btnConvert1.Visible = false;
btnConvert2.Visible = true;
DataTable dt2 = new DataTable();
for (int i = 0; i <= dt.Rows.Count; i++)
{
dt2.Columns.Add();
}
for (int i = 0; i < dt.Columns.Count; i++)
{
dt2.Rows.Add();
dt2.Rows[i][0] = 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);
}
else
{
btnConvert1.Visible = true;
btnConvert2.Visible = false;
BindGrid(dt, false);
}
}
Screenshot