Reputation: 495
I have a List<MyClass>
which is a datasource to a BindingSource
. That BindingSource
is in turn the datasource to my datagridview
.
When I change a value in my underlying list, and call datagridview.Refresh()
the change in value is reflected.
However, when I sort my underlying list, the change is NOT reflected in my datagridview
. I expect/want the rows in the datagridview
to be in the order of my underlying list.
I've tried doing a BindingSource.RestetBindings()
which doesn't work, and has other implications I don't like.
I don't imagine I should be sorting the actual rows in the DGV, but I could be wrong? It would seem silly to sort the datasource and then have to sort the DGV too.
Upvotes: 1
Views: 1489
Reputation: 5266
Seems to work fine:
public class Person : IComparable<Person> {
public int Id { get; set; }
public String Name { get; set; }
public int CompareTo(Person other) {
return Name.CompareTo(other.Name);
}
}
DataGridView dgv = new DataGridView();
List<Person> pList = new List<Person>();
BindingSource pSource = new BindingSource();
public MyForm() {
pList.Add(new Person { Id = 1, Name = "Bob" });
pList.Add(new Person { Id = 2, Name = "Alan" });
pSource.DataSource = pList;
dgv.DataSource = pSource;
FlowLayoutPanel p = new FlowLayoutPanel { Dock = DockStyle.Fill };
p.Controls.Add(btn);
p.Controls.Add(dgv);
Controls.Add(p);
btn.Click += btn_Click;
}
void btn_Click(object sender, EventArgs e) {
pList.Sort();
dgv.Refresh();
}
Upvotes: 1