程序运行正常,但Ascending和Descending按钮不起作用。包含表中所有数据的DataGridView看起来相同但未排序。它假设按标题排序。也许它确实排序但不刷新DataGridView?
private void btnSortAscendingRecords_Click(object sender, EventArgs e)
{
DataView TitlesDataView = new DataView(booksDataset1.Books);
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
}
答案 0 :(得分:1)
您必须将DataSource设置为刚刚创建的新DataView。我假设这是Windows窗体应用程序?
如果是,那么:
[YourDataGridView].DataSource = TitlesDataView;
答案 1 :(得分:0)
当 DataGridView 绑定到 DataSource ( DataView,BindingSource,Table,DataSet +“tablename”)时,它会引用<强>数据视图即可。获取对此DataView的引用,并根据需要设置排序(和过滤器):
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;
}
注意:排序和过滤器中使用的列名对应于DataTable中的列名, DataGridView中的列名是用于在dgv中显示单元格的控件的名称。 您可以像这样在DataView中使用列名:
string colName = dgv.Columns[colIdx].DataPropertyName
取决于您希望如何跟踪排序列(colSequence,colName,asc / desc,dgvColIdx),您可以决定如何构建Sort和Filter表达式并在dgv中设置SortGlyph(为简单起见,我制作了硬编码)。