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 t开发者_如何学JAVAhe inserted record will be displayed directy on the right place of the datagridview.
Who can help me with a tip.
Thanks.
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?
Maybe try handling the BindingSource.ListChanged event?
This code snippet works very well, and fast enough for most purposes...
int iColNumber = 3; //e.g., sorting on the 3rd column of the DGV
MyBindingSource.DataSource = MyBindingList.OrderByDescending(o => o.GetType().GetProperty(MyDataGridView.Columns[iColNumber].Name).GetValue(o));
精彩评论