2011-04-17 81 views
1

好的,所以我使用此代碼從組合框選擇填充checkedlistbox。我需要對checkedlistbox和組合框進行排序。現在,我正在對它們進行排序。我認爲在數據庫中對它們進行重新排序會做到這一點,但它們是基於創建時間而不是其他任何東西出現的。從數據庫中填充排序列表框

這個第一個填充組合框,我需要它按字母順序排序。

private void cmbDatabaseFill() 
    { 
     string conStr = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=myDB.mdb"; 
     try 
     { 
      myConn = new OleDbConnection(conStr); 
      myConn.Open(); 
     } 
     catch (OleDbException ex) 
     { 
      MessageBox.Show("Error in connection ..." + ex.Message); 
      return; 
     } 

     string sqlStr = "SELECT * FROM Index;"; 

     dAdapter = new OleDbDataAdapter(sqlStr, myConn); 

     dset = new DataSet(); 

     dAdapter.TableMappings.Add("Table", "Index"); 

     dAdapter.Fill(dset); 

     this.dviewmanager = dset.DefaultViewManager; 

     this.cmbIndex.DataSource = this.dviewmanager; 

     this.cmbIndex.DisplayMember = "Index.list"; 

     this.myConn.Close(); 
    } 

這一個是爲checkedlistbox,我需要它根據數據庫中的「訂單」字段排序。 「訂單」欄只包含顯示內容應該顯示的順序的數字。現在

private void clbDatabaseFill() 
    { 
     string newTableName = cmbIndex.Text.Replace(" ", ""); 

     string conStr = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=myDB.mdb"; 
     try 
     { 
      myConn2 = new OleDbConnection(conStr); 
      myConn2.Open(); 
     } 
     catch (OleDbException ex) 
     { 
      MessageBox.Show("Error in connection ..." + ex.Message); 
     } 

     string sqlStr = "SELECT * FROM " + newTableName + ";"; 

     dAdapter2 = new OleDbDataAdapter(sqlStr, myConn2); 

     dset2 = new DataSet(); 

     dAdapter2.TableMappings.Add("Table", newTableName); 

     try 
     { 
      dAdapter2.Fill(dset2); 
     } 
     catch (System.Exception) 
     { 
      return; 
     } 

     this.dviewmanager2 = dset2.DefaultViewManager; 

     this.clbList.DataSource = this.dviewmanager2; 

     this.clbList.DisplayMember = newTableName + ".Name"; 

     this.myConn2.Close(); 
    } 

,就像我說的,一切都顯示和功能正常,我抓住我從checkedlistbox需要在以後使用DataRowView的,而不是綁定valuemember引用在數據庫中的列名的值,因爲我處理每行有多個值。最大的問題是它不是基於「Order」列顯示的,或者它在數據庫中的顯示方式。有沒有簡單的方法來完成這兩種不同的排序方法?

回答

0

嘗試增加這些線路各自的組合框和checklistbox之前設置.DataSource屬性:

this.dviewmanager.DataViewSettings["Index"].Sort = "Order DESC"; 

this.dviewmanager2.DataViewSettings[newTableName].Sort = "Order DESC"; 

DataViewSettings["Index"]DataViewSettings[newTableName]指名爲數據表的DataSet中。

Order DESC表示要排序的列名爲Order,而DESC顯然意味着頂部的最大值。根據您的要求移除DESC或指定ASC。

+0

這工作完美!非常感謝。這是在這個應用程序準備好之前剩下的所有東西,而且這個工作很好。也不會減慢速度。現在他們都被分類爲ASC,並且一切都很好。謝謝。 – James 2011-04-17 05:09:37

+0

@詹姆斯:不客氣!很高興有幫助! – 2011-04-17 05:20:45