2011-06-09 16 views
1

我正在使用ASP.NET Grid View來顯示錶格中的數據。 我想按照用戶選擇的特定順序排列列。asp.net:grid view:排列

說明: 我想根據用戶的輸入交換列(即索引3變爲5等),這可能嗎?

我曾嘗試使用此代碼..但它仍然提供了意想不到的結果

 var boundF0 = (BoundField)GVReport.Columns[0]; 
     var boundF5 = (BoundField)GVReport.Columns[5]; 

     GVReport.Columns.RemoveAt(0); 
     GVReport.Columns.RemoveAt(5); 

     GVReport.Columns.Insert(0, boundF5); 
     GVReport.Columns.Insert(5, boundF0); 

任何想法出了什麼問題?

+0

我覺得問題肯定是因爲你試圖操縱GridView的對象,而不是你綁定到數據gridview對象 – Brett 2011-06-09 12:29:53

+0

你能解釋一下意外的結果嗎? – naveen 2011-06-10 03:37:59

回答

0

您可以使用http://www.devexpress.com/爲Gridview或以下是傳統方法的代碼。

DataTable dt = new DataTable(); 
dt.Columns.Add("Column1", typeof(string)); 
dt.Columns.Add("Column2", typeof(string)); 

while (dr.Read()) 
dt.Rows.Add(new object[] { dr[0], dr[1] }); 

Grid1.DataSource = dt; 
Grid2.DataBind(); 

This would give you a grid with Column1 and Column2. Once you changed 
the order you can do following 

If (order_changed) 
{ 
dt.Columns.Add("Column2", typeof(string)); 
dt.Columns.Add("Column1", typeof(string)); 
while (dr.Read()) 
dt.Rows.Add(new object[] { dr[1], dr[0] }); 
} 

else 
{ 

dt.Columns.Add("Column1", typeof(string)); 
dt.Columns.Add("Column2", typeof(string)); 
while (dr.Read()) 
dt.Rows.Add(new object[] { dr[0], dr[1] }); 
} 

Now you would get a grid with Column2 and Column1 

設置網格的AutoGenerateColumns屬性爲true,你會得到列