4

i have a list

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

where "SalesDetail" is a class. i have a button (add) and my code on click event of add button is SalesList.Add(details); where details is object of class SalesDetail which contains public variables with {set; and get;}

but when i try to retrieve each item of the list then i only get the last item. my code retrieving each item is

foreach(SalesDetail sd in SalesList)
{

    messageBox.show(SalesList);

}

in my class SalesDetail i have following code

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

i want to retrieve each item from list and save it to database i would like to know where i have made mistake while retrieving the data.. please help Regards bunzitop

4

3 回答 3

2

SalesList是类型。您应该sd在循环中使用(这是变化的值)。

于 2013-03-26T12:49:52.653 回答
2

You need to use the sd object which refers to the current item in SalesList

Try:

foreach(SalesDetail sd in SalesList)
{

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

}

From chat:

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);

}
于 2013-03-26T12:49:06.557 回答
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);
于 2013-03-26T13:19:53.963 回答