2013-03-26 59 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);