2015-12-02 29 views
2

我已經編寫了一些代碼來簡單地從一個緊湊型SQL服務器(4.0)中提取數據庫信息。在那一刻,我剛剛分離每個項目檢索幾個空格,但我想知道我如何可以拉每個項目,並使其對應的標題。這裏的初始化:在列表視圖中提取和分割數據庫項目

InitializeListView

private void InitializeListView() 
{ 
    // Set the view to show details. 
    lbxBugged.View = View.Details; 

    // Allow the user to rearrange columns. 
    lbxBugged.AllowColumnReorder = true; 

    // Select the item and subitems when selection is made. 
    lbxBugged.FullRowSelect = true; 

    // Display grid lines. 
    lbxBugged.GridLines = true; 

    // Sort the items in the list in ascending order. 
    lbxBugged.Sorting = SortOrder.Ascending; 

    // Attach Subitems to the ListView 

    lbxBugged.Columns.Add("Code", 300, HorizontalAlignment.Left); 
    lbxBugged.Columns.Add("Description", 200, HorizontalAlignment.Left); 
    lbxBugged.Columns.Add("Author", 120, HorizontalAlignment.Left); 
} 

我已經試過:

最初使用列表框,但我讀過多列的則必須使用列表視圖。所以我換成了一個listview,但它並沒有填充列表。不太確定哪個是最好的方式去做這件事。

我已經初始化了listview,所以它顯示了標題,我只需要知道如何用相應的數據庫信息填充這些空格。

populateListBox(從我使用一個列表框時,一直在研究,但只能找人從一個實際的數據庫填充與數據庫信息的列表視圖,而不是一個小型的數據庫。)

public void populateListBox() 
{ 
    String query = "SELECT Bug_Code, Bug_Description, Bug_Author FROM tblBugs"; 
    SqlCeCommand mySqlCommand = new SqlCeCommand(query, mySqlConnection); 
    try 
    { 
     mySqlConnection.Open(); 
     SqlCeDataReader mySqlDataReader = mySqlCommand.ExecuteReader(); 
     lbxBugged.Items.Clear(); 
     while (mySqlDataReader.Read()) 
     { 
      lbxBugged.Items.Add(mySqlDataReader["Bug_Code"].ToString() + "  " + mySqlDataReader["Bug_Description"].ToString() + "  " + mySqlDataReader["Bug_Author"].ToString()); 
     } 
    } 
    catch (SqlCeException) 
    { 
     MessageBox.Show("Error populating list box"); 
    } 
} 
+2

ListViewItem對象有一個SubItems集合屬性。 – LarsTech

+0

雖然我會如何使用SQL compact來做這件事? –

+0

我不確定爲什麼SQL壓縮部分是個問題。 'var lvi = new ListViewItem(new string [] {rdr [「Bug_Code」]。ToString(),rdr [「Description」]。ToString(),etc。});' – LarsTech

回答

2

首次採用列表視圖所以忘記使用項目&子項目。這是我完成的方法,爲其他任何人掙扎:

public void populateListView() 
      { 
       lbxBugged.Items.Clear(); 
       SqlCeCommand cm = new SqlCeCommand("SELECT Bug_ID, Bug_Code, Bug_Description, Bug_Author FROM tblBugs ORDER BY Bug_ID ASC", mySqlConnection); 

       try 
       { 
        mySqlConnection.Open(); 
        SqlCeDataReader dr = cm.ExecuteReader(); 
        while (dr.Read()) 
        { 
         ListViewItem item = new ListViewItem(dr["Bug_ID"].ToString()); 
         item.SubItems.Add(dr["Bug_Code"].ToString()); 
         item.SubItems.Add(dr["Bug_Description"].ToString()); 
         item.SubItems.Add(dr["Bug_Author"].ToString()); 

         lbxBugged.Items.Add(item); 
        } 
       } 
       catch (Exception ex) 
       { 
        MessageBox.Show(ex.Message, "Error"); 
       } 


      }