2013-01-23 54 views
1

我正在爲datagridview排序選項combobox太慢並且排序不起作用

private DataClasses1DataContext db = new DataClasses1DataContext(); 
private int numberOfObjectsPerPage = 20; 
private int CurrentPageIndex = 1; 
private string ordering = "c.name ascending"; 

private void Form1_Load(object sender, EventArgs e) 
{ 
    GetData(CurrentPageIndex);    
} 

private void GetData(int page) 
{ 
    page = page - 1;    

    var query = (from c in db.enterprise 
    orderby ordering 
        select new { c.id, c.name, c.phone, c.email, c.type, c.city }) 
        .Skip(numberOfObjectsPerPage * page).Take(numberOfObjectsPerPage); 

    dataGridView1.DataSource = query; 
} 

private void orderBtn_Click(object sender, EventArgs e) 
{ 
    if (orderCB.SelectedIndex == 1) 
    { 
     ordering = "c.name descending"; 
    } 
    else if (orderCB.SelectedIndex == 2) 
    { 
     ordering = "c.id ascending"; 
    } 
    else if (orderCB.SelectedIndex == 3) 
    { 
     ordering = "c.id descending"; 
    } 
    else 
    { 
     ordering = "c.name ascending"; 
    } 

    GetData(CurrentPageIndex);    
} 

我在這裏遇到了兩個問題。

  1. 我目前的數據是關於2.500的行。我正在使用分頁,因此它將顯示20數據/頁面,但在加載datagridview時仍然太慢。什麼可能是錯的?
  2. 我的訂購按鈕不起作用。

這是一個用C#我的第一次,也許我錯過的東西在這裏:d

更新

所以我改變了我的代碼,建議從the_joric

Func<IEnumerable<cooperations>, IEnumerable<cooperations>> ordering = t => t; 

我改變DBType到基於此參考的合作(希望我是對的:D) enter image description here

但是後來我的DataGridView不顯示任何東西,我得到的是這樣的

System.Linq.Enumerable+<TakeIterator>d__3a`1[<>f__AnonymousType0`7[System.Int32,System.String,System.String,System.String,System.String,System.String,System.String]] 
A first chance exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll 
+0

對於性能問題,你還是回來了整個2500行到客戶端上的每個查詢。 –

+0

我認爲它在MySQL中的工作方式與限制和偏移量相同:D – l1th1um

回答

2

,因爲你是常量字符串鍵整理您的按鈕不起作用。 orderby是一種適用於OrderBy<>()方法的合成糖,它應該帶有關鍵選擇器。在你的情況下,選擇器總是一個對所有項目都是相同的字符串。但它應該是一個函數,你的對象,並返回其關鍵

您可以嘗試類似的東西:

// instead of DbType your should use the type of db.enterprise 
Func<IEnumerable<DbType>, IEnumerable<DbType>> ordering= t => t; // default ordering (as it is) 
... 
var query = (from c in ordering(db.enterprise) 
        select new { c.id, c.name, c.phone, c.email, c.type, c.city }) 
        .Skip(numberOfObjectsPerPage * page).Take(numberOfObjectsPerPage); 
... 
// in your button click method 
if (orderCB.SelectedIndex == 1) 
{ 

    ordering = t => t.OrderByDescending(i => i.name); 
} 
else if (orderCB.SelectedIndex == 2) 
{ 
    ordering = t => t.OrderBy(i => i.id); 
} 
... 
+0

感謝您的解釋。但是現在我得到了異常('System.ArgumentOutOfRangeException was unhandled',Index超出範圍,必須是非負數,小於集合的大小)=>'dataGridView1.Columns [0] .Visible = false ' – l1th1um

+0

請參閱更新:D – l1th1um

+0

好像你沒有在你的網格列 –