List item in database

I have a list

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

where "SalesDetail" is the class. I have a (add) button, and my code when I click the add button is SalesList.Add (details); where details is an object of the SalesDetail class that contains public variables with {set; and get;}

but when I try to get every item in the list, I get only the last item. my code extracting every element

 foreach(SalesDetail sd in SalesList) { messageBox.show(SalesList); } 

in my SalesDetail class I have the following code

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

I want to get each item from a list and store it in a database. I would like to know where I made a mistake when retrieving data. please help Regards bunzitop

+4
source share
3 answers

You need to use an sd object that references 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); } 
+2
source

SalesList - type. You should use sd (which is a variable value) in your loop.

+2
source

First, the definition of your class is incorrect, because you omit the types of your Brand and Product properties, and the public visibility public must be lowercase.

To use ToString() , you need to override the method in your class:

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

Then you can use Linq to list the Aggregate and display its contents.

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

All Articles