2015-12-02 32 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"); 
       } 


      }