Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

c# - How to display rows as columns in DataGridView?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...