【问题标题】:list item to database将项目列表到数据库
【发布时间】:2013-03-26 12:48:15
【问题描述】:

我有一个清单

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

【问题讨论】:

    标签: c# .net database list generic-list


    【解决方案1】:

    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() 但它也没有显示列表中的任何项目..
      • 我使用代码SalesList.Add(details); 将我的项目添加到列表中,详细信息是包含Public string Brand {Set; Get;} ` Public String Product {set; Get;}` 是我添加到列表的方式正确吗??
      • 试试 sd.Brand 和 sd.Product
      • 我也试过sd.Brand,但每次在循环中,这只会给我最后输入的项目,,我仍然无法获得其他项目.. :(
      • @user2174542 听起来您的 SalesList 没有您期望的所有项目。在 foreach 循环中放置一个断点并检查 SalesList 并查看它包含哪些项目,检查它们是否不同或完全相同。
      【解决方案3】:

      首先,您的类定义是错误的,因为您省略了 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);
      

      【讨论】:

        猜你喜欢
        • 2017-02-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-03-13
        • 2013-06-03
        • 1970-01-01
        • 2016-11-24
        相关资源
        最近更新 更多