将列表项存储到数据库中。

4
我有一个列表。
List<SalesDetail>  SalesList = new List<SalesDetail>();
SalesDetail detail = new SalesDetail();  

"SalesDetail"是一个类。我有一个按钮(添加),当我点击该按钮时,我的代码如下:

SalesList.Add(details);

其中details是SalesDetail类的对象,它包含公共变量{set;和get;}。

但是,当我尝试检索列表中的每个项目时,我只会得到最后一个项目。我的检索代码如下:

foreach(SalesDetail sd in SalesList)
{

    messageBox.show(SalesList);

}

在我的SalesDetail类中,我有以下代码。
Public string Brand{get; set;}
Public string Product{get; set;}

我希望能从列表中检索每个项目并将其保存到数据库中。我想知道在检索数据时我犯了哪些错误。请帮忙。谢谢。祝好。

3个回答

2

SalesList是一种数据类型。在循环中,应该使用sd(即变化的值)。


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

}

我按照你说的尝试了,但是出现了错误信息“无法转换为字符串”,我还尝试了sd.ToString(),但它也没有显示列表中的任何项。 - Bunzitop
我使用以下代码将我的项目添加到列表中: SalesList.Add(details); 其中,details是一个包含以下内容的类对象: public string Brand {set; get;} public string Product {set; get;} 请问我的添加方式是否正确? - Bunzitop
尝试使用 sd.Brand 和 sd.Product。 - Darren
我也尝试了 sd.Brand,但每次在循环中它只会给出最后输入的项目,我仍然无法得到其他项目... :( - Bunzitop
@user2174542,听起来你的SalesList列表中并不包含所有你期望的项。在foreach循环中设置一个断点,检查SalesList列表并查看它包含哪些项,检查它们是否不同或者完全相同。 - Darren
让我们在聊天中继续这个讨论:http://chat.stackoverflow.com/rooms/26945/discussion-between-bunzitop-and-darren-davies - Bunzitop

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接