Wednesday, May 9, 2012

Column wise GridView

Ever been in a situation where you had to represnted data in GridView where entries will be column wise.
For example if you queried the database and populated the GridView like this:

ID  Name  Age
1   John      20
2   Mark     30

And you had to represent it as:

ID          1         2
Name     John    Mark
Age        20       30

This format is generally used when you are displaying comparison data. The standard ASP.Net gridview doesnt give this functionality by default. But you can do it by querying the data in original format in a datatable and then transposing it and then assigning it to gridview. I have done it by writing this function:


public static DataTable TransposeDataTable(DataTable dt)
    {
        DataTable dtNew = new DataTable();
        for (int i = 0; i < dt.Rows.Count + 1; i++)
        {
            dtNew.Columns.Add(i.ToString());
        }
        for (int i = 0; i < dt.Columns.Count; i++)
        {
            DataRow dr = dtNew.NewRow();
            dtNew.Rows.Add(dr);
            dr[0] = dt.Columns[i].ColumnName;
        }
        for (int i = 0; i < dtNew.Rows.Count; i++)
        {
            for (int j = 1; j < dtNew.Columns.Count; j++)
            {
                dtNew.Rows[i][j] = dt.Rows[j - 1][i];
            }
        }
        return dtNew;
    }

This will return the following datatable for the above example:

0            1         2
ID          1         2
Name     John    Mark
Age        20       30

Here I am creating the header of the datatable with numbers starting from 0. Since you dont need header for this kind of data representation in gridview you can assign it to the gridview and just set the 'ShowHeader' property of gridview to false.

No comments:

Post a Comment