Datagridview / BindingSource and sorted: add an entry to the end of the list

This will be a dumb question, but I have a datagridview with a BindingSource as the data source.

The bindingSources.Datasource property is its own BindingList with sorting support. It all works.

But when the record is inserted into the sorted list, it will be placed at the end of the datagridiview. After updating (for example, by clicking the mouse), the record will be placed in the right place.

So, I think I forgot to implement something or call to make sure that the inserted record will be displayed right in the right place of the datagridview.

Who can help me with a hint.

Thanks.

+4
source share
2 answers

This works for me with the following code.

Sorry for the rough code - I am just showing key snippets, but I can provide a more complete example if you need to.

I have a SortableBindingList _names bound to my DataGridView. Then in my form I have a button with new names added to the Click handler even. This works great to add the name kevin between joe and pete.

private SortableBindingList<Names> _names; public Form1() { InitializeComponent(); _names = new SortableBindingList<Names>(); _names.Add(new Names() { Name = "joe" }); _names.Add(new Names() { Name = "pete" }); DataGridViewTextBoxColumn col1 = new DataGridViewTextBoxColumn(); col1.DataPropertyName = "Name"; dataGridView1.Columns.Add(col1); dataGridView1.DataSource = _names; } private void button1_Click(object sender, EventArgs e) { _names.Add(new Names(){Name = "kevin"}); dataGridView1.Sort(dataGridView1.Columns[0], ListSortDirection.Descending); } public class Names { public string Name { get; set; } } 

So, the main thing is that I sort my DataGridView after adding to the list.

I could also provide IComparer in my .Sort () call - the default comparator simply compares with .ToString ()

Interestingly, in my example, when inserting an element, the following also works:

 private void button1_Click(object sender, EventArgs e) { //_names.Add(new Names(){Name = "kevin"}); _names.Insert(1, new Names() { Name = "kevin" }); // dataGridView1.Sort(dataGridView1.Columns[0], ListSortDirection.Descending); } 

Just pasting an element in the right place is enough for the grid to display a list sorted correctly. I use the same SortableBindingList as you, the one shown on MartinWilley.com.

Could your problem be what you add, not paste?

0
source

Maybe try to handle the BindingSource.ListChanged event?

0
source

Source: https://habr.com/ru/post/1299043/


All Articles