Display gridview row as coloumn in asp.net

Description:-

In this example we explain that how to convert GridView columns to row or convert GridView columns to GridView row in asp.net. Sometime in project there are many clients that required the GridView data should be displayed in reverse format means GridView columns display as GridView row and GridView rows should be displayed as GridView columns.

Default.aspx.cs:-

Protected void Page_Load(object sender, EventArgs e)
{
  if (!Page.IsPostBack)
  {
    PopulateGrid();
  }
}

protectedvoidPopulateGrid()
{
  DataTabledt = newDataTable();
  dt.Columns.Add("Emp_Id", typeof(Int32));
  dt.Columns.Add("Emp_Name", typeof(string));
  dt.Columns.Add("Designation", typeof(string));
  dt.Columns.Add("Email-ID", typeof(string));
  dt.Columns.Add("MobileNo", typeof(Int64));
  DataRowdtrow = dt.NewRow();
  // Create First Row 
  dtrow["Emp_Id"] = 1;
  dtrow["Emp_Name"] = "Umesh";
  dtrow["Designation"] = "MCA";
  dtrow["Email-ID"] = "Umesh@gmail.com";
  dtrow["MobileNo"] = 9485768594;
  dt.Rows.Add(dtrow);
  dtrow = dt.NewRow();
  // Create Second Row 
  dtrow["Emp_Id"] = 2;
  dtrow["Emp_Name"] = "Chirag";
  dtrow["Designation"] = "ITI";
  dtrow["Email-ID"] = "Chirag@gmail.com";
  dtrow["MobileNo"] = 2345987456;
  dt.Rows.Add(dtrow);
  dtrow = dt.NewRow();
  // Create third Row 
  dtrow["Emp_Id"] = 3;
  dtrow["Emp_Name"] = "Kirit";
  dtrow["Designation"] = "MCA";
  dtrow["Email-ID"] = "Kirit@gmail.com";
  dtrow["MobileNo"] = 2038945456;
  dt.Rows.Add(dtrow);
  dtrow = dt.NewRow();
  // Create Fourth Row 
  dtrow["Emp_Id"] = 4;
  dtrow["Emp_Name"] = "Harpal";
  dtrow["Designation"] = "PGDCA";
  dtrow["Email-ID"] = "Harpal@gmail.com";
  dtrow["MobileNo"] = 2345898764;
  dt.Rows.Add(dtrow);
  gv_Defaultgrid.DataSource = dt;
  gv_Defaultgrid.DataBind();
  gv_convertedgrid.DataSource = ConvertColumnsAsRows(dt);
  gv_convertedgrid.DataBind();
  gv_convertedgrid.HeaderRow.Visible = false;
}

Protected void gv_convertedgrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
  if (e.Row.RowType == DataControlRowType.DataRow)
  {
    e.Row.Cells[0].CssClass = "gridcss";
  }
}

// This function is used to convert columns to rows 
Public DataTable ConvertColumnsAsRows(DataTabledt)
{
  DataTabledt_temp = newDataTable();
  //Convert all the rows to columns 
  for (int i = 0; i <= dt.Rows.Count; i++)
  {
    dt_temp.Columns.Add(Convert.ToString(i));
  }
  DataRowdr;
  // Convert All the Columns to Rows 
  for (int j = 0; j <dt.Columns.Count; j++)
  {
    dr = dt_temp.NewRow();
    dr[0] = dt.Columns[j].ToString();
    for (int k = 1; k <= dt.Rows.Count; k++)
    dr[k] = dt.Rows[k - 1][j];
    dt_temp.Rows.Add(dr);
  }
  returndt_temp;
}

Related Posts

Previous
Next Post »

Thanks for comments.....