Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Datagridview/BindingSource and sorted: add record at end of list

This will be a stupid question but I have a datagridview with a BindingSource as datasource.

The bindingSources.Datasource is a own BindingList with sort support. All this works.

But when a record will be inserted in the sorted list, then it will placed at the end of the datagridiview. After a refresh (example with the mouse click), the record will be placed on the right place.

So, I think that I forget something to implementat or call to ensure that the inserted record will be displayed directy on the right place of the datagridview.

Who can help me with a tip.

Thanks.

like image 271
robertpnl Avatar asked Nov 15 '22 13:11

robertpnl


1 Answers

I have this working with the following code.

Please excuse the rough code - I'm just showing the key pieces, but I can provide a more complete example if you need.

I have a SortableBindingList _names which is bound to my DataGridView. Then on my form I have a button, with a new names added in the Click even handler. This is working fine 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 key thing is that I sort my dataGridView after adding to the list.

I could have also provided an IComparer in my .Sort() call - the default comparer is just comparing on .ToString()

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

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);
}

Simply inserting the item at the right place is enough to make the grid display the list sorted correctly. I'm using the same SortableBindingList as you, the one shown at MartinWilley.com.

Could your problem be that you are adding rather then inserting?

like image 144
David Hall Avatar answered Dec 26 '22 23:12

David Hall