2013-03-01 114 views
2

在winform中,我試圖將返回的數據集值與定義的值進行比較,但是我收到以下錯誤。比較數據集的值

Visual Studio Error

在下面的代碼,我從列表框傳遞字符串到GetStock方法

public bool checkStock() 
     { 
      foreach (var listBoxItem in listBox1.Items) 
      { 
       if (Convert.ToInt32(GetStock(listBoxItem.ToString())) == 0) 
       { 
        MessageBox.Show(listBoxItem.ToString() + " not in Stock!. Please delete the item before proceeding"); 
        return false; 
       } 
      } 
      return true; 
     } 

代碼GetStock()

public DataSet GetStock(string product) 
     { 
      DataSet dataSet = new DataSet(); 
      OleDbConnection oleConn = new OleDbConnection(connString); 

      try 
      { 
       oleConn.Open(); 
       string sql = "SELECT [Quantity] FROM [Product] WHERE [Product Name]='" + product + "'"; 
       OleDbDataAdapter dataAdapter = new OleDbDataAdapter(sql, oleConn); 
       dataAdapter.Fill(dataSet, "Product"); 
      } 
      catch (Exception ex) 
      { 
       Console.WriteLine(ex.ToString()); 
      } 
      finally 
      { 
       oleConn.Close(); 
      } 
      if (dataSet.Tables["Product"].Rows.Count <= 0) 
       return null; 

      return dataSet; 
     } 

    } 
} 

在數據庫中的 「數量」是字符串格式。

回答

4

GetStock返回DataSet,但你把它傳遞給Convert.ToInt32

if (Convert.ToInt32(GetStock(listBoxItem.ToString())) == 0) 

你可能想是這樣的:

int stockCount = GetStockQuantity(listBoxItem.ToString()); 
if (stockCount == 0) 
{ 
    MessageBox.Show(listBoxItem.ToString() + " not in Stock!. Please delete the item before proceeding"); 
} 

下面是修改的方法(請注意,我使用參數)

public int GetStockQuantity(string product) 
{ 
    int quantity = 0; 
    string sql = "SELECT TOP 1 [Quantity] FROM [Product] WHERE [Product Name] = ?"; 
    using(var oleConn = new OleDbConnection(connString)) 
    using(var cmd = new OleDbCommand(sql , oleConn)) 
    { 
     cmd.Parameters.AddWithValue("?", product); 
     try 
     { 
      oleConn.Open(); 
      object obj_quantity = cmd.ExecuteScalar(); 
      if(obj_quantity != null) 
       // "In database the "Quantity" is in string format." 
       // Change it to int if possible 
       int.Parse((string)obj_quantity); 
     } 
     catch (Exception ex) 
     { 
      Console.WriteLine(ex.ToString()); 
     } 
    } 
    return quantity; 
} 
+0

但在這裏我指的是0到當數量變爲0 – 2013-03-01 12:27:33

+0

@AmritSharma:編輯我的答案,但在我看來,最好是返回一個空'DataTable'或'DataSet'。由於您選擇的是單個表,我會返回一個DataTable,DataSet會建議它包含(或可以包含)多個表。 – 2013-03-01 12:29:07

+0

實現了你的解決方案,但是即使我在數據庫中設置數量爲0,代碼也會返回true – 2013-03-01 12:31:40

1

The GetStock方法返回DataSet,但您需要實際的int值。試試這個:

Convert.ToInt32(GetStock(listBoxItem.ToString()).Tables["Product"].Rows[0]["Quantity"]) 
0

試試這個方法:

var count = GetStock(listBoxItem.ToString()); 

if (count > 0) 
{ 
    //TODO: other stuff 
} 
else 
{ 
    MessageBox.Show(listBoxItem.ToString() + " not in Stock!. Please delete the item before proceeding"); 
}