Last week, when I wanted to display a
DataGrid in a horizontal manner (vertical rows), I thought there may be some property in
DataGrid to flip it, but it wasn’t the case or may be I couldn’t find it. I read online articles and forums but didn’t get very useful or easy solutions. One of the solutions I found was to nest a
DataList into a
DataSet but I didn’t find this easy; and the other was all together a new control called xrepeater but I found mine easier than the two of them.
Let’s say you have a dataset which you want to render through a datagrid but you don’t want to show horizontal rows, instead you want to show the rows vertically. There may be lot of cases when you want to do that, for example comparison between two things on several criteria (Column headings) or when you have just one or two rows to show then you would prefer the vertical rows for more clarity. Here is how the idea of flipping the table comes in.
The idea is to flip all the entries inside each table of the dataset. This is not a very good solution but it works fine. I wrote a method which takes a
DataSet as a parameter and returns a new
DataSet with all tables flipped and now you just have to bind this
DataSet’s tables to the
DataGrid as you do normally and
DataGrid renders vertical rows.
Old Table looks like below.
New DataTable looks like this
Please note that in flipped table there are column headings as integer numbers, so when bind you it to the datagrid, and set the property
ShowHeader=false; you are all set to render the vertical dataRows properly.
Here is the code for
FlipDataSet method, is in the code behind file for me. In method
FlipDataSet, I am doing flipping of dataset and in
BindData, I am binding the first table of it to the
DataGrid. This is all:
private void BindData()
DataSet ds = this.GetDetail(); DataSet new_ds = FlipDataSet(ds); DataView my_DataView = new_ds.Tables.DefaultView;
this.my_DataGrid.DataSource = my_DataView;
public DataSet FlipDataSet(DataSet my_DataSet)
DataSet ds = new DataSet();
foreach(DataTable dt in my_DataSet.Tables)
DataTable table = new DataTable();
for(int i=0; i<=dt.Rows.Count; i++)
for(int k=0; k<dt.Columns.Count; k++)
r = table.NewRow();
r = dt.Columns[k].ToString();
for(int j=1; j<=dt.Rows.Count; j++)
r[j] = dt.Rows[j-1][k];
Thanks for reading and please send any questions or comments you may have (I am sure you will).