2014-02-08 33 views
0

中的WebMethod和顯示所有的數據庫值我試圖循環,並通過從我的網絡服務將WebMethod顯示出在我的數據庫中的所有值我有。然後我試圖以asmx格式正確顯示它。無法環路ASMX

public class eCommerce 
{ 
    public string ItemName { get; set; } 
    public string cost { get; set; } 
} 

我試圖使用get set來獲取相應的數據。

下面我用.hasRowwhile loop也試過。但是,它只顯示並返回數據庫中的第一行數據。

[WebMethod] 
public eCommerce ItemAvailable(string itemcategory) 
{ 
    eCommerce Item = new eCommerce(); 

    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString); 
    con.Open(); 
    SqlCommand cmd = new SqlCommand("SELECT ItemName, Cost FROM eCommerce Where Category ='"+itemcategory+"'", con); 
    SqlDataReader dr = cmd.ExecuteReader(); 
    if (dr.HasRows) 
    { 
     while (dr.Read()) 
     { 
      Item.ItemName = Convert.ToString(dr["ItemName"]); 
      Item.cost = Convert.ToString(dr["Cost"]); 
     } 
    } 
    con.Close(); 

    return Item; 
} 

我是否遺漏了任何能夠循環並將所有值返回給數據庫的值。

回答

1

的while循環中的每個循環重寫Item。它看起來像你想要返回多個電子商務實例,所以你爲什麼不返回一個列表。

[WebMethod] 
public List<eCommerce> ItemAvailable(string itemcategory) 
{ 

    List<eCommerce> allItems = new List<eCommerce>(); 

    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString); 
    con.Open(); 
    SqlCommand cmd = new SqlCommand("SELECT ItemName, Cost FROM eCommerce Where Category ='"+itemcategory+"'", con); 
    SqlDataReader dr = cmd.ExecuteReader(); 
    if (dr.HasRows) 
    { 
     while (dr.Read()) 
     { 
      item = new eCommerce(); 
      item.ItemName = Convert.ToString(dr["ItemName"]); 
      item.cost = Convert.ToString(dr["Cost"]); 

      allItems.add(item); 
     } 
    } 
    con.Close(); 

    return allItems; 
} 
+0

+1的福氣。 – Rahul