太慢,排序不起作用

时间:2013-01-23 15:46:17

标签: c# sorting datagridview

我正在combobox上进行排序选项datagridview

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. 我的订购按钮不起作用。
  3. 这是我第一次使用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
    

1 个答案:

答案 0 :(得分:2)

您的按钮不起作用,因为您按常量字符串键排序。 orderbyOrderBy<>()方法的一个合成糖,应该使用键选择器。在您的情况下,选择器始终是一个对所有项都相同的字符串。但它应该是一个获取对象并返回其键的函数

您可以尝试这样的事情:

// 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); 
}
...