1

我正在comboboxdatagridview.

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) 在此处输入图像描述

但是后来我的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
4

1 回答 1

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); 
}
...
于 2013-01-23T16:41:52.817 回答