I need to shuffle the GridControl's DataSource. I use this property in a UserControl:
private List<Song> _songsDataSource;
public List<Song> SongsDataSource
{
get { return _songsDataSource; }
set
{
_songsDataSource = value;
if (!value.IsNull())
{
SongsBindingList = new BindingList<Song>(value);
songsBinding.DataSource = SongsBindingList;
}
}
}
Then i use a method that i clone, shuffle and append to the SongsDataSou开发者_如何学Gorce property:
List<Song> newList = HelpClasses.Shuffle((List<Song>) SongsDataSource.Clone());
SongsDataSource = newList;
public static List<Song> Shuffle(List<Song> source)
{
for (int i = source.Count - 1; i > 0; i--)
{
int n = rng.Next(i + 1);
Song tmp = source[n];
source[n] = source[i - 1];
source[i - 1] = tmp;
}
return source;
}
Strange thing is that it doesn't seem to reflect the changes to the GridControl even i use the GridControl.RefreshDataSource() method after set the SongsDataSource method. If i check the DataSource order, shuffle was happened successfully.
Thank you.
Since you've changed the object originally set as a DataSource, calling RefreshDataSource()
won't do any good cause you can't refresh something that's no longer there. Your problem is here:
List<Song> newList = HelpClasses.Shuffle((List<Song>) SongsDataSource.Clone());
SongsDataSource = newList; // the reference has changed, the grid doesn't know what to do when RefreshDataSource() is called.
You can pass the list as it is, without the need of cloning it. Also surround the Shuffle()
method call with gridControl.BeginUpdate()
end gridControl.EndUpdate()
to prevent any updates to the grid while the elements of the DataSource
are changing.
I had such problems with DevExpress GridControl. I think, that this situation caused by GridView(http://documentation.devexpress.com/#WindowsForms/clsDevExpressXtraGridViewsGridGridViewtopic), which creates automaticly for each GridControl. This is part of GridControl responsible for visualization of DataSource. If you need to change DataSource try:
GridView.Columns.Clear();
GridControl.DataSource = You_New_DataSource;
GridView.RefreshData();
GridControl.RefreshDataSource();
精彩评论