我正在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);
}
我在这里遇到两个问题。
2.500
行。我正在使用分页,因此它会显示20
数据/页面,但在加载datagridview
时仍然太慢。可能有什么不对?这是我第一次使用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
答案 0 :(得分: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);
}
...