2013-03-26 57 views
4

我有一個列表列表項數據庫

List<SalesDetail> SalesList = new List<SalesDetail>(); 
SalesDetail detail = new SalesDetail(); 

其中「的salesdetail」是一類。我有一個按鈕(添加),我的代碼點擊事件添加按鈕是 SalesList.Add(details); 其中細節是類SalesDetail的對象,其中包含具有{set;並得到;}

但是當我嘗試檢索列表中的每個項目,然後我只得到最後一個項目。 我的代碼檢索每個產品

foreach(SalesDetail sd in SalesList) 
{ 

    messageBox.show(SalesList); 

} 
在我的課

的salesdetail我有以下代碼

Public string Brand{get; set;} 
Public string Product{get; set;} 

我想要從列表中的每個項目,將其保存到數據庫 我想知道在哪裏已犯的錯誤,而檢索數據.. 請幫助 問候 bunzitop

回答

2

您需要使用sd對象是指將當前項中SalesList

嘗試:

foreach(SalesDetail sd in SalesList) 
{ 

    messageBox.show(sd.Brand); 
    messageBox.show(sd.Product); 

} 

從聊天:

List<SalesDetail> SalesList = new List<SalesDetail>(); 

public void button1_click() { 

    SalesDetail detail = new SalesDetail(); 
    detail.Brand = textBox1.Text 
    detail.Product= textBox2.Text` 
    SalesList.Add(detail); 

} 
+0

我試圖按照你說的,但錯誤信息出現「無法轉換爲字符串」我也試過sd.ToString(),但它也沒有顯示在列表中的任何項目.. – Bunzitop 2013-03-26 13:08:00

+0

添加我的項目代碼清單 'SalesList.Add(details);' 和細節是類的對象,其中包含 'Public string Brand {Set; Get;}' '公共字符串產品{set;獲取;}' 是我的方式添加到列表正確?? – Bunzitop 2013-03-26 13:09:51

+0

嘗試sd.Brand和sd.Product – 2013-03-26 13:15:25

2

SalesList是類型。您應該在循環中使用sd(這是變化的值)。

0

首先,由於您省略了BrandProduct屬性的類型,並且public可見性修飾符應該是小寫,因此您的類定義是錯誤的。

爲了使用ToString()你需要覆蓋的方法類:

public class SalesDetail 
{ 
    public string Brand {get; set;} 
    public string Product {get; set;} 

    public override string ToString() 
    { 
     return string.Format("Brand: {0}, Product {1}", Brand, Product); 
    } 
} 

然後你可以使用LINQ Aggregate列表並顯示它的內容。

var items = SalesList.Select(s => s.ToString()).Aggregate((s, s1) => s + Environment.NewLine + s1); 
MessageBox.Show(items);