C#, datagridview, how to flip row and column?

The datagridview has attached bindingsource which contains one set of class object (loaded from serializer)

I wish to flip row and column so that 1st column is member name and 2nd column is data (string or int), rather than across the screen.

I note there is no rotate or flip feature.

Please include demo code in C#.
Richard PayneChief Technology EngineerAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Éric MoreauSenior .Net ConsultantCommented:
check my article on a Transpose method for a DataTable object.

The downloadable demo contains C# code: http://emoreau.com/Entries/Articles/2012/02/ADONet-DataTable-transpose.aspx
anarki_jimbelSenior DeveloperCommented:
I believe there is a simpler approach. DataGridView - is just a VIEW, and we should be able to manipulate the view, not the underlying table. You may use "DisplayIndex" property.

private void AdjustColumnOrder()
    customersDataGridView.Columns["CustomerID"].Visible = false;
    customersDataGridView.Columns["ContactName"].DisplayIndex = 0;
    customersDataGridView.Columns["ContactTitle"].DisplayIndex = 1;
    customersDataGridView.Columns["City"].DisplayIndex = 2;
    customersDataGridView.Columns["Country"].DisplayIndex = 3;
    customersDataGridView.Columns["CompanyName"].DisplayIndex = 4;

Open in new window

Richard PayneChief Technology EngineerAuthor Commented:
Hi Eric

I have bindingsource in datagridview which raised exception because of casting error

An unhandled exception of type 'System.InvalidCastException' occurred in UDT_Term_FFT.exe

Additional information: Unable to cast object of type 'System.Windows.Forms.BindingSource' to type 'System.Data.DataTable'.

I tried a fix but did not work

// DataTable dtSource = (DataTable)dataGridView1.DataSource;
DataTable dtSource = (DataTable)((BindingSource)dataGridView1.DataSource).DataSource;

Open in new window

An unhandled exception of type 'System.InvalidCastException' occurred in UDT_Term_FFT.exe

Additional information: Unable to cast object of type 'System.ComponentModel.BindingList`1[UDT_Term_FFT.AppDGVExample+ConfigurationZZ]' to type 'System.Data.DataTable'.

Below is where bindingsource1

        #region //========================================================== AppDGVExample_Load (when window open)
        private void AppDGVExample_Load(object sender, EventArgs e)
            bindingSource1.DataSource = configb;
            dataGridView1.DataSource = bindingSource1;
            DGV_TransposeTable();       // Flip Row and Column


Open in new window

OWASP: Avoiding Hacker Tricks

Learn to build secure applications from the mindset of the hacker and avoid being exploited.

Richard PayneChief Technology EngineerAuthor Commented:
I forget to add

        BindingList<ConfigurationZZ> configb;                   // Binding List genetic type.
Éric MoreauSenior .Net ConsultantCommented:
>>I have bindingsource in datagridview which raised exception because of casting error

Since your grid's datasource is not a DataTable (BindingList<ConfigurationZZ> configb;), you will not be able to cast it as a DataTable!

You can try to cast it as BindingList.
Richard PayneChief Technology EngineerAuthor Commented:

Can you make up example?

Richard PayneChief Technology EngineerAuthor Commented:
Is there way for CS code to work on BindingList<> to transpose the grid?
Éric MoreauSenior .Net ConsultantCommented:
Here is something I put up for you:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
    public partial class Form1 : Form
        public Form1()

        private void btnLoad_Click(object sender, EventArgs e)
            BindingList<ConfigurationZZ> configb;
            configb = new BindingList<ConfigurationZZ>
                new ConfigurationZZ {ID = 1, Value = "Value 1"},
                new ConfigurationZZ {ID = 2, Value = "Value 2"},
                new ConfigurationZZ {ID = 3, Value = "Value 3"}

            BindingSource bindingSource1 = new BindingSource();
            bindingSource1.DataSource = configb;

            grdOriginal.DataSource = bindingSource1;

        private void btnPivot_Click(object sender, EventArgs e)
            BindingSource bs = (BindingSource) grdOriginal.DataSource;
            BindingList<ConfigurationZZ> configb = (BindingList<ConfigurationZZ>) bs.DataSource;
            DataTable dtSource = ToDataTable(configb);

            //Create the datatable
            DataTable dtnew = new DataTable();
            //Create a column to hold the product name
            //Add the columns using the first column of each row to become the new column caption
            for (int i = 0; i <= dtSource.Rows.Count - 1; i++)

            for (int i = 1; i <= dtSource.Columns.Count - 1; i++)
                //Create an empty row for each column of the source table
                DataRow dr = dtnew.NewRow();

                //use the column name to populate the first row cell
                dr[0] = dtSource.Columns[i].ColumnName;
                //the real transpose is this loop
                for (int j = 0; j <= dtSource.Rows.Count - 1; j++)
                    dr[j + 1] = dtSource.Rows[j][i].ToString();

                //add the newly created row to the new DataTable
            //Show the new transposed table
            grdPivot.DataSource = dtnew;

        private DataTable ToDataTable<T>(IList<T> data)
            PropertyDescriptorCollection props =
            DataTable table = new DataTable();
            for (int i = 0; i < props.Count; i++)
                PropertyDescriptor prop = props[i];
                table.Columns.Add(prop.Name, prop.PropertyType);
            object[] values = new object[props.Count];
            foreach (T item in data)
                for (int i = 0; i < values.Length; i++)
                    values[i] = props[i].GetValue(item);
            return table;

    public class ConfigurationZZ
        public int ID { get; set; }
        public string Value { get; set; }

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Richard PayneChief Technology EngineerAuthor Commented:
Thank Eric, you a pal!
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.