2013-07-25 77 views
0

我正在做一個數據綁定winform與C#連接Northwind數據庫 目標是提供數據在winform gridview,當我點擊每個單元格時,數據將是顯示在相應的文本框中。數據綁定winform代碼錯誤「InvalidCastException未處理」

class Connection   
{ 

    String connectionstring = "Data Source=ECHREIPCPC0671\\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=True"; 

    public ArrayList GetAllProduct(int ProductID) 
    { 
     using (var connection = new SqlConnection(connectionstring)) { 
      connection.Open(); 

      String query = "SELECT * FROM Products WHERE ProductID = " + ProductID; 
      using (var command = new SqlCommand(query, connection)) 
      { 
       var reader = command.ExecuteReader(); 
       var list = new ArrayList(); 
       while (reader.Read()) 
       { 
        String productname = reader.GetString(1); 
        String quantityperunit = reader.GetString(2); 
        Decimal unitprice = reader.GetDecimal(3); 

        list.Add(productname); 
        list.Add(quantityperunit); 
        list.Add(unitprice); 

       } 
       connection.Close(); 
       reader.Close(); 
       return list; 
      } 

這是新的I類添加到閱讀和數據獲取到的winform,在這裏,當我執行的代碼,總是有誤差

「無法投類型的對象「 System.Int32' 爲鍵入System.String'

代碼後:`字符串單位數量= reader.GetString(2);

我應該糾正我的代碼是否anybo? dy能幫助我嗎?

PS:在form1.cs中,我添加了使用此類中成員的函數。

 private void FillTextfield(int ProductID) 
    { 
     list = sqlCon.GetAllProduct(ProductID); 
     textProductName.Text = list[0].ToString(); 
     textQuantityPerUnit.Text = list[1].ToString(); 
     textUnitPrice.Text = list[2].ToString(); 

    } 

    private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) 
    { 
     var currentRowIndex = dataGridView1.SelectedCells[0].RowIndex; 
     int currentIndex = (int)dataGridView1.Rows[currentRowIndex].Cells[0].Value; 
     FillTextfield(currentIndex); 
    } 

} 

我不認爲是單位數量的int類型,因爲這個細胞內的數據是一樣的東西「12盎司瓶」等

+0

什麼第三欄的類型和單元格值是什麼? –

+0

在數據網格視圖中,我有4列,productID,ProductName,QuantityPerUnit和UnitPrice,數據庫中的類型是int,nvarchar(40),nvarchar(20),money。 – SeaJay

回答

0

嘗試

String quantityperunit=reader.GetString(2).ToString(); 

reader.GetString(2)被取你有一些整型數據,你試圖把這些數據放入一個字符串變量中,這會引發你一個異常。

0

quantityperunit是一個整數類型。

int quantityperunit = int.Parse(reader.GetString(2).ToString()); 
0

「無法投類型 'System.Int32' 的對象鍵入 'System.String'」

你可以試試這個..

String quantityperunit=reader.GetInt32(2).ToString(); 
+0

謝謝,如果我嘗試了你的代碼,然後在下一行,出現另一個錯誤「指定的轉換無效」。這是否意味着從數據庫中的貨幣類型轉換爲十進制是錯誤的? – SeaJay

+0

@SeaJay ..你可以嘗試一樣的轉換到那一行.. – matzone

+0

嗨〜謝謝你的建議,但下一個是SQL中的moneytype,我想使用String unitprice = reader.GetSqlMoney(3).ToString( );但它仍然行不通,你有新的想法嗎? – SeaJay