2011-03-30 70 views
2

程序運行良好,但升序和降序按鈕不起任何作用。包含來自表的所有數據的DataGridView看起來都是相同的,並且沒有排序。它假設按標題排序。也許它排序,但不刷新DataGridView?DataView不會在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 
     } 

回答

1

您必須將DataSource設置爲您剛剛創建的新DataView。我認爲這是Windows窗體應用程序?

如果是這樣,則:

[YourDataGridView].DataSource = TitlesDataView; 
+0

我在找什麼。 – HelloWorld 2011-03-30 16:43:07

+0

@HelloWorld酷,很高興它幫助 – 2011-03-31 05:39:07

0

的DataGridView結合到它參考,到數據視圖所有情況下,的DataSource數據視圖,BindingSource的,表,數據集+ 「表名」)。獲取參考這個數據視圖,並設置排序(和過濾)如你所願:

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中顯示單元格的控件的名稱。 你可以在數據視圖中使用這樣的列名:

string colName = dgv.Columns[colIdx].DataPropertyName 

的你要如何跟蹤排序列Depends中(colSequence,COLNAME,遞增/遞減,dgvColIdx),你可以決定如何排序構建和篩選表達式並在dgv中設置SortGlyph(爲簡單起見,我製作了硬編碼)。