DataView doesn't sort ascending or descending in DataGridView
The program runs fine but Ascending and Descending buttons don't do anything. The DataGridView with all the data from a table looks the same and not sorted. It suppose to sort by Title. Maybe it does sort but doesn't refresh the DataGridView?
private void btnSortAscendingRecords_Click(object sender, EventArgs e)
{
DataView TitlesDataView = new DataView(booksDataset1.Books);
开发者_如何学C TitlesDataView.Sort = "BookTitle ASC";
//sort asc titles in videosgrid
}
private void btnSortDescendingRecords_Click(object sender, EventArgs e)
{
DataView TitlesDataView = new DataView(booksDataset1.Books);
TitlesDataView.Sort = "BookTitle DESC";
//sort descending titles in videosgrid
}
You have to set the DataSource to the new DataView you just created. I assume this is windows forms application?
If so then:
[YourDataGridView].DataSource = TitlesDataView;
When DataGridView binds to the DataSource (DataView, BindingSource, Table, DataSet+"tablename") in all cases it refere to the DataView. Get reference to this DataView and set Sort (and Filter) as you wish:
DataView dv = null;
CurrencyManager cm = (CurrencyManager)(dgv.BindingContext[dgv.DataSource, dgv.DataMember]);
if (cm.List is BindingSource)
{
// In case of BindingSource it may be chain of BindingSources+relations
BindingSource bs = (BindingSource)cm.List;
while (bs.List is BindingSource)
{ bs = bs.List as BindingSource; }
if (bs.List is DataView)
{ dv = bs.List as DataView; }
}
else if (cm.List is DataView)
{
// dgv bind to the DataView, Table or DataSet+"tablename"
dv = cm.List as DataView;
}
if (dv != null)
{
dv.Sort = "somedate desc, firstname";
// dv.Filter = "lastname = 'Smith' OR lastname = 'Doe'";
// You can Set the Glyphs something like this:
int somedateColIdx = 5; // somedate
int firstnameColIdx = 3; // firstname
dgv.Columns[somedateColIdx].HeaderCell.SortGlyphDirection = SortOrder.Descending;
dgv.Columns[firstnameColIdx].HeaderCell.SortGlyphDirection = SortOrder.Ascending;
}
Note: Column names used in Sort and Filter correspond to the column names in DataTable, Column names in DataGridView are the names of controls used to display cells in dgv. You can get column name used in DataView like this:
string colName = dgv.Columns[colIdx].DataPropertyName
Depends of how do you want to track sorted columns (colSequence, colName, asc/desc, dgvColIdx) you may decide how to build Sort and Filter expression and set the SortGlyph in dgv (I made hardcode for simplicity).
精彩评论