1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Swapping Rows and columns

Discussion in 'ASP.NET' started by Beaustark, Aug 14, 2009.

  1. Beaustark

    Beaustark New Member

    Joined:
    Aug 14, 2009
    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    0
    Hi,
    I want show the database table column as a row in the gridview. How can i so that?
     
  2. shency

    shency New Member

    Joined:
    Oct 25, 2008
    Messages:
    14
    Likes Received:
    0
    Trophy Points:
    0
    Ask naimish, he is really good at .Net
     
  3. naimish

    naimish New Member

    Joined:
    Jun 29, 2009
    Messages:
    1,046
    Likes Received:
    18
    Trophy Points:
    0
    Occupation:
    Software Engineer
    Location:
    On Earth
    Try with below example :)

     
  4. Ami Desai

    Ami Desai Member

    Joined:
    Jan 5, 2017
    Messages:
    30
    Likes Received:
    14
    Trophy Points:
    8
    Location:
    Ahmedabad
    Home Page:
    Hi,

    You can check this

    To flip columns into rows :
    Code:
    public static DataTable FlipDataTable(DataTable dt)
    {
                DataTable table = new 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;
    }
    Now to bind the original DataTable to a GridView gvColumnsAsColumns and the flipped DataTable to gvColumnsAsRows, add the following code in the page_load event
    Code:
    //Bind datatable with columns as columns
      gvColumnsAsColumns.DataSource = dt;
      gvColumnsAsColumns.DataBind();
    //Bind datatable with columns as rows
      gvColumnsAsRows.DataSource = FlipDataTable(dt);
      gvColumnsAsRows.DataBind();
      gvColumnsAsRows.HeaderRow.Visible = false;

    Thanks
     
    shabbir likes this.

Share This Page