2012-03-18 55 views
3

我試圖顯示在VS 2008中使用datagridview從sql數據庫檢索到的數據集。但我需要垂直顯示數據而不是水平顯示數據。這是我在開始時所做的。如何在DataGridView中將行顯示爲列?

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"; 

我搜索並閱讀了一些線程,但沒有一個工作。任何人都可以幫助我垂直顯示在datagridview中檢索到的數據?

回答

9

試試這個:

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; 
+0

非常感謝蒂姆。那就像魅力一樣。 Thnx再次.... !!!你拯救我的一天:) – 2012-03-18 12:47:17

相關問題