2012-02-28 94 views
1

我的代码出了什么问题?此代码是从我转换为C#我的VB .NET程序,但得到一个错误。它是用来与用途需要的搜索选择数据库中的数据。这里是我的代码:Listview填充方法出错

public void byItemCode(ListView LV, String SearchBox) 
     { 
      try 
      { 
       con.Open(); 

       ds.Tables.Add(dt); 
       OleDbDataAdapter da = new OleDbDataAdapter("SELECT ItemCode, Title, Genre, Film, YearReleased, Classification, NumberOfDiscs FROM tblDVDInventory WHERE ItemCode LIKE '%" + SearchBox + "%' ORDER BY Title", con); 
       da.Fill(dt); 

       int num = 1; 

       for (int ctr = 0; ctr <= dt.Rows.Count - 1; ctr++) 
       { 
        ListViewItem Item = new ListViewItem(); 
        Item.Text = num; 
        Item.SubItems.Add(dt.Rows[ctr]["ItemCode"]); 
        Item.SubItems.Add(dt.Rows[ctr]["Title"]); 
        Item.SubItems.Add(dt.Rows[ctr]["Genre"]); 
        Item.SubItems.Add(dt.Rows[ctr]["Film"]); 
        Item.SubItems.Add(dt.Rows[ctr]["YearReleased"]); 
        Item.SubItems.Add(dt.Rows[ctr]["Classification"]); 
        Item.SubItems.Add(dt.Rows[ctr]["NumberOfDiscs"]); 
        LV.Items.Add(Item); 

        num = num + 1; 
       } 

       con.Close(); 
      } 
      catch (Exception error) 
      { 
       MessageBox.Show(error.ToString()); 
      } 
     } 

然后搜索表单上,这里是代码:

var Search = new SearchMethods(); 

       if (cmbSearchBy.Text == "Item Code") 
       { 
        lvwInventory.Items.Clear(); 
        Search.byItemCode(lvwInventory, txtSearch.Text); 
       } 

我不知道如何做到这一点在C#中的正确方法?谢谢。

+0

您可能需要初始化SubItems – Joe 2012-02-28 02:15:37

+0

很可能是Joe的答案,但如果您想要一个确切的答案,您应该发布错误。 – zclark 2012-02-28 02:19:09

+0

'System.Windows.Forms.ListViewItem.ListViewSubCollectionItems。(Add)String的最佳重载方法匹配。 – 2012-02-28 02:22:42

回答

1

您的Datatable将填充Object s,而不是string s。 ListView想要string s,所以您需要致电ToString()或类型转换为string类型。如果您不知道期望的类型或者您不期望string s,请使用ToString();如果您期望string,请使用(string)转换。

+0

我现在明白了,它只是添加ToString()到我添加的每一行,像这样: Item.Text = num.ToString(); Item.SubItems.Add(dt.Rows [ctr] [“ItemCode”]。ToString()); – 2012-02-28 02:24:18