我正在使用Windows窗体DataGridView来显示MyObject对象的通用列表.
首先,我将此集合包装到BindingSourceCollection中,然后:
dataGridView.DataSource = myBindingSource;
Run Code Online (Sandbox Code Playgroud)
我想要做的是允许用户通过单击表示MyObject中具体属性的列标题对列进行排序.
我读过一些文章,我应该在绑定之前进行排序.但是,如果我想实时对列进行排序,那么它就无法帮助我.
问题是,我到底需要做什么,所以我可以看到 DataGridView中的排序箭头,我可以对每一列进行排序?
我有一个返回IList <T>的函数,它是DataGridView的DataSource.我了解到DataGridView不会对IList进行排序.我读了这个stackoverflow问答,我正在尝试实现SortableBindingList.我一定做错了,因为我的DataGridView是空的.我还尝试使用TextBox从SortableBindingSource访问一个元素,但也没有.
using Microsoft.SqlServer.Management.Controls;
public partial class Form1 : Form
{
IBusinessLayer businessLayer;
IList<Category> categories;
SortableBindingList<Category> catSortable;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
businessLayer = new BusinessLayer();
categories = businessLayer.GetAllCategories();
catSortable = new SortableBindingList<Category>(categories);
categoryBindingSource.DataSource = catSortable;
categoryDataGridView.DataSource = categoryBindingSource;
textBox1.Text = catSortable[0].CategoryName;
}
}
Run Code Online (Sandbox Code Playgroud)
我检查了Microsoft.SqlServer.Management.Controls,这看起来不错吗?
namespace Microsoft.SqlServer.Management.Controls
{
public class SortableBindingList<T> : BindingList<T>
{
public SortableBindingList();
public SortableBindingList(IList<T> list);
protected override bool IsSortedCore { get; }
protected override ListSortDirection …Run Code Online (Sandbox Code Playgroud) 我BindingList<T>在我的Windows窗体中使用了一个包含" IComparable<Contact>"联系人对象列表的窗体.现在我希望用户能够按网格中显示的任何列进行排序.
在线MSDN上有一种描述如何实现基于BindingList<T>允许排序的自定义集合的方法.但是,是否有一个Sort-event或者某些东西可以在DataGridView中捕获(或者,甚至更好,在BindingSource上)以使用自定义代码对底层集合进行排序?
我真的不喜欢MSDN描述的方式.另一种方法是我可以轻松地将LINQ查询应用于集合.
我知道关于这个话题有很多问题.我经历了所有这些,但似乎没有任何帮助.
如何通过单击列标题进行排序?
我应该如何修改此代码来完成这项工作?
public partial class Form1 : Form
{
public Form1()
{
List<MyClass> list = new List<MyClass>();
list.Add(new MyClass("Peter", 1202));
list.Add(new MyClass("James", 292));
list.Add(new MyClass("Bond", 23));
BindingSource bs = new BindingSource();
bs.DataSource = list;
DataGridView dg = new DataGridView();
DataGridViewTextBoxColumn c = new DataGridViewTextBoxColumn();
c.Name = "name";
c.DataPropertyName = "Name";
dg.Columns.Add(c);
c = new DataGridViewTextBoxColumn();
c.Name = "number";
c.DataPropertyName = "Number";
dg.Columns.Add(c);
dg.DataSource = bs;
this.Controls.Add((Control)dg);
}
}
class MyClass:IComparable<MyClass>
{
public string Name { get; set; }
public …Run Code Online (Sandbox Code Playgroud) 我正在尝试将WinForms DataGridView绑定到EntityCollection<T>EntityFramework4对象.麻烦的是,我无法弄清楚如何对其进行排序(自动).
我正在做的就是将BindingSource的DataSource属性设置为实体的集合.
MyBindingSource.DataSource = CurrentItem.InvoiceNotes;
我真的希望有一个简单的配置,我可以添加到它,以使其工作; 我真的不想将我的EF Collection包装在一个新的BindingList容器中.
c# datagridview winforms entity-framework-4 entitycollection