How to display rows as columns in DataGridView?

2020-02-07 03:48发布

问题:

I'm trying to display set of data which have retrieved from the sql database using a datagridview in VS 2008. But I need to display data vertically rather than horizontally. This is what I have done at the beginning.

con.Open();
SqlCommand cmd = new SqlCommand("proc_SearchProfile", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@scute_id", SqlDbType.VarChar, (10)).Value = val;
SqlDataAdapter adapt = new SqlDataAdapter(cmd);
DataSet dset = new DataSet();

adapt.Fill(dset, "Profile");
this.dataGridView1.DataSource = dset;
this.dataGridView1.DataMember = "Profile";

I searched and read a few threads but none of those work. Can anyone help me on displaying retrieved data in a datagridview vertically?

回答1:

Try this:

var tbl = dset.Tables["Profile"]:
var swappedTable = new DataTable();
for (int i = 0; i <= tbl.Rows.Count; i++)
{
    swappedTable.Columns.Add(Convert.ToString(i));
}
for (int col = 0; col < tbl.Columns.Count; col++)
{
    var r = swappedTable.NewRow();
    r[0] = tbl.Columns[col].ToString();
    for (int j = 1; j <= tbl.Rows.Count; j++)
        r[j] = tbl.Rows[j - 1][col];

    swappedTable.Rows.Add(r);
}
dataGridView1.DataSource = swappedTable;